这是我的员工类。
public class Employee
{
public string LastName { get; set; }
public string FirstName { get; set; }
public bool Fire { get; set; }
}
这就是XAML的设置方式。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid Loaded="EmployeesGridLoaded">
<DataGrid x:Name="gEmployees" HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" AlternatingRowBackground="LightBlue" AlternationCount="2" AutoGenerateColumns="False" Grid.Row="0">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Fire" Binding="{Binding Fire}" Width="1*" />
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" Width="3*" />
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" Width="3*" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
最后这是EmployeesGridLoaded方法。
private void EmployeesGridLoaded(object sender, RoutedEventArgs e)
{
List<Employee> Employees = new List<Employee>()
{
new Employee() { Fire = false, LastName = "Silly", FirstName = "Dude" },
new Employee() { Fire = false, LastName = "Mean", FirstName = "Person" },
};
gEmployees.ItemsSource = Employees;
}
}
问题是当我第一次点击Fire复选框时,它不会立即将状态更改为立即检查。我必须再次单击以更改其状态以进行检查。它可能是第一次选择行。无论如何,当我点击这个单元格并且在网格中没有选择行时,是否第一次检查它?
答案 0 :(得分:3)
替换这行代码:
<DataGridCheckBoxColumn Header="Fire" Binding="{Binding Fire}" Width="1*" />
使用:
<DataGridTemplateColumn Header="Fire" Width="1*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Fire, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>