我有一个看起来像这样的设置:
// myDG is a DataGrid whose columns are DataGridTextColumn
ObservableCollection<MyItem> myOC;
// myOC is populated with some new MyItem
myDG.ItemsSource = myOC;
Run Code Online (Sandbox Code Playgroud)
其中MyItem工具INotifyPropertyChanged.当用户将值输入单元格时,正确捕获的方法是什么?
我试着追赶PropertyChanged的MyItemS,但我在后台周期性也更新值(这个想法是,当用户手动编辑值,标志被触发,告诉周期性的计算以避免覆盖手动输入的数据).所以PropertyChanged抓住了一切,包括我不想要的定期更新.我想可以使这个工作(通过在我进行定期计算时设置一个标志,然后在PropertyChanged事件处理程序上检查是否缺少标志 - 但我想知道是否有更简单的解决方案.)
我尝试过捕获,myDG.CurrentCellChanged但每次用户更改单元格选择时都会触发,而不是在编辑单元格内容时.
编辑:这是XAML:
<DataGrid x:Name="myDG" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="10,10,182,0" VerticalAlignment="Top" Height="329" ClipboardCopyMode="IncludeHeader">
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding Prop1}" IsReadOnly="True"/>
<DataGridTextColumn Header="Col2" Binding="{Binding Prop2}" IsReadOnly="False"/>
</DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
这是MyItem实现(使用Fody/PropertyChanged):
[ImplementPropertyChanged]
class MyItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public MyItem()
{
Prop1 = Prop2 = "";
}
}
Run Code Online (Sandbox Code Playgroud)
jca*_*cai 29
解决方案是抓住CellEditEnding事件.
// In initialization
myDG.CellEditEnding += myDG_CellEditEnding;
void myDG_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
var column = e.Column as DataGridBoundColumn;
if (column != null)
{
var bindingPath = (column.Binding as Binding).Path.Path;
if (bindingPath == "Col2")
{
int rowIndex = e.Row.GetIndex();
var el = e.EditingElement as TextBox;
// rowIndex has the row index
// bindingPath has the column's binding
// el.Text has the new, user-entered value
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30184 次 |
| 最近记录: |