从Datagrid中的选定单元格获取值 [英] Get Value from a selected cell in Datagrid
问题描述
我想从DataGrid中的选定单元格中检索字符串。到目前为止,我想出了这个:
I want to retrieve a string from a selected cell in a DataGrid. So far I came up with this:
<DataGrid ItemsSource="{Binding Products}" SelectedItem="{Binding SelectedProduct, Mode=OneWayToSource}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=ProductKey}" ClipBoardContentBinding="{x:Null}" Header="Product Key" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding Path=Price}" ClipBoardContentBinding="{x:Null}" Header="Price" IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
我只需要ProductKey。我发现的相当多的例子只会导致视图背后的代码,我想避免这种情况。为简单起见,我们假设我的模型有2个属性; ProductKey(字符串)和Price(int)这是我的视图模型:
I only need the ProductKey. A fair number of the examples I have found only leads to code behind in the view, I'd like to avoid that. For simplicity, Let's assume my model has 2 properties; "ProductKey"(string) and "Price" (int) Here is my view model:
private List<Product> _products;
public List<Product> Products
{
get {return _products;}
}
public ProductViewModel()
{
_products.Add(new Product{ProductKey="101",Price=100});
_products.Add(new Product{ProductKey="102",Price=25});
_products.Add(new Product{ProductKey="301",Price=75});
}
private Product _selectedproduct;
public Product SelectedProduct
{
get {return _selectedproduct;}
set
{
if (_selectedproduct != value)
_selectedproduct = value;
}
}
我尝试在set SelectedProduct中设置一个断点,它似乎没有启动每当我点击datagrid的ProductKey列时,
I tried putting a break point in set SelectedProduct, it doesn't seem to launch whenever I click on the ProductKey column of the datagrid.
推荐答案
DataGrid的CurrentCell属性需要绑定到视图模型而不是SelectedItem。模式设置为单向,因此当选择更改时,视图模型中的属性会更新。
CurrentCell property of the DataGrid needs to be bound to the view model instead of SelectedItem. Mode is set to one way so when the selection is changed, the property in the viewmodel is updated.
<datagrid itemssource="{Binding Products}" currentcell="{Binding CurrentCell, Mode=OneWayToSource}">
</datagrid>
< br $>
private CurrentCellInfo _currentcell;
public CurrentCellInfo CurrentCell
{
get {return _currentcell;}
set
{
if (value.Column != null && value != _currentcell)
{
_currentcell = value;
_selectedproduct = (Product)_currentcell.Item;
// optional, in my case, i didn't need to because I am not binding SelectedProduct to the view
// OnPropertyChanged("SelectedProduct");
}
}
}
剩下的就是从_selectedproduct中获取任何属性的值
All that is left is to get the value of whatever properties from _selectedproduct
似乎你必须设置TwoWay
模式,但我不是专家......请参阅:如何使用MVVM处理数据网格单元更改? [ ^ 一>]。
我建议读这个: MVVM和WPF DataGrid [ ^ ]
Seems you have to setTwoWay
mode, but i'm not a specialist... Please, see: How do you handle data grid cell changes with MVVM?[^].
I'd suggest to read this: MVVM and the WPF DataGrid[^]
这篇关于从Datagrid中的选定单元格获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!