我在数据网格中有事件按下键。但是我不能从更新的单元格中获取当前值。我需要知道每一个字符改变的值。
if (DataGrid1.SelectedIndex == -1 || e.Key == Key.Enter || e.Key == Key.Tab || e.Key == Key.Escape)
return;
var thisValueIsNull = DataGrid1.CurrentCell.Item as Person;
var thisValueIsBeforeStartUpdate = DataGrid1.SelectedItem as Person;
我应该怎么做才能得到这个值?
代码xmal:
<DataGrid x:Name="DataGrid1" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
AutoGenerateColumns="False" Grid.RowSpan="2" CanUserAddRows="False" LayoutUpdated="DataGrid1_LayoutUpdated" RowHeaderWidth="0" KeyDown="DataGrid1_KeyDown">
<DataGrid.Columns>
<DataGridTextColumn x:Name="column1" Header="Name" Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn x:Name="column2" Header="SecondName" Binding="{Binding SecondName}" Width="*"/>
<DataGridTextColumn x:Name="column3" Header="Age" Binding="{Binding Age}" Width="*"/>
<DataGridTextColumn x:Name="column4" Header="Country" Binding="{Binding Country}" Width="*"/>
<DataGridTextColumn x:Name="column5" Header="City" Binding="{Binding City}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
编辑:
public partial class MainWindow : Window
{
List<Person> person = new List<Person>();
public MainWindow()
{
InitializeComponent();
person.Add(new Person() { Name = "Abb", SecondName = "AA" });
person.Add(new Person() { Name = "Bbb", SecondName = "BB" });
person.Add(new Person() { Name = "Ccc", SecondName = "CC" });
DataGrid1.ItemsSource = person;
}
private void WordsDataGrid_KeyDown(object sender, KeyEventArgs e)
{
}
}
public class Person
{
public string Name { get; set; }
public string SecondName { get; set; }
public int Age { get; set; }
}
Xaml:
<DataGrid x:Name="DataGrid1" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
AutoGenerateColumns="False" Grid.RowSpan="2" CanUserAddRows="False" RowHeaderWidth="0" KeyDown="WordsDataGrid_KeyDown">
<DataGrid.Columns>
<DataGridTextColumn x:Name="column1" Header="Name" Binding="{Binding Name}" Width="*"/>
<DataGridTextColumn x:Name="column2" Header="SecondName" Binding="{Binding SecondName}" Width="*"/>
<DataGridTextColumn x:Name="column3" Header="Age" Binding="{Binding Age}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
在编辑中,你有代码可以添加到程序中。它可以是其他事件,让我在每次更改后获取当前值,而无需单击输入或更改焦点。
解决方案:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Name}" KeyUp="TextBox_KeyUp"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
1条答案
按热度按时间kpbwa7wx1#
您可以在KeyDown事件中使用以下内容:
最好的祝愿,阿什坎