如何解决DataGrid中的WPF组合框:在当前行失去焦点之后,组合框值变回旧值
在我的WPF DataGrid
中,数据来自Employee
类(如下所示)。 Employee类中的StateName
列是DataGrid内部的Combobox
。组合框是从State
类填充的(如下所示)。数据正确显示(如下图1所示)。但是,当我从组合框中选择一个不同的状态(如下图2所示)并将光标移动到网格的下一行时,新选择的State
值将变回默认值。例如,当我在第一行中将组合框值从Iowa
更改为Ohio
并移动到光标到另一行时,第一行State
列的值会变回从Ohio
到Iowa
。 问题:我还没有实现任何事件,但是我想知道为什么将光标移到另一行后状态列的值又变回原始值?
<Window x:Class="WPF_DataGridCombobox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPF_DataGridCombobox"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<local:StateList x:Key="ListOfStates"/>
</Window.Resources>
<Grid>
<DataGrid x:Name="dgEmplyees" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTemplateColumn Header="State Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding StateName}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="cmbState" ItemsSource="{StaticResource ListOfStates}" DisplayMemberPath="StateName" SelectedValuePath="StateCode" IsEditable="False" IsReadOnly="True" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
加载MainWindow时:
组合框演示更改状态:
Employee.cs :
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string StateName { get; set; }
}
State.cs :
public class State
{
public string StateName { get; set; }
public string StateCode { get; set; }
}
StateList.cs :
public StateList()
{
Add(new State { StateName = "Iowa",StateCode = "IA" });
Add(new State { StateName = "Nebraska",StateCode = "NE" });
Add(new State { StateName = "Ohio",StateCode = "OH" });
Add(new State { StateName = "Virginia",StateCode = "VA" });
}
MainWindow.xaml.cs :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { EmployeeId = 1,Name = "Tom Smith",StateName = "Iowa" });
employees.Add(new Employee { EmployeeId = 2,Name = "Jane Price",StateName = "Nebraska" });
employees.Add(new Employee { EmployeeId = 3,Name = "Chris Puin",StateName = "Ohio" });
employees.Add(new Employee { EmployeeId = 4,Name = "Amber Friedman",StateName = "Virginia" });
dgEmplyees.ItemsSource = employees;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。