任何人都知道如何通过ViewModel更改数据网格的SelectedValue。如果我们更改View然后它将触发VM,但反之则不然。
答案 0 :(得分:3)
public ViewModel()
{
PriceLogs = new ObservableCollection<PriceLog>();
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(2), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(20), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(50), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(80), Price = 600 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(80), Price = 300 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(2), Price = 200 });
//Here is how you can change selected Item from ViewModel
SelectedPriceProlog = PriceLogs.Last();
// SelectedPriceProlog = PriceLogs[2];
}
public ObservableCollection<PriceLog> PriceLogs { get; set; }
private PriceLog selectedPriceProlog;
public PriceLog SelectedPriceProlog
{
get { return selectedPriceProlog; }
set
{
selectedPriceProlog = value;
Notify("SelectedPriceProlog");
}
}
<DataGrid ItemsSource="{Binding PriceLogs}" SelectedItem="{Binding SelectedPriceProlog, Mode=TwoWay}">
如何设置选定值
public ViewModel()
{
PriceLogs = new ObservableCollection<PriceLog>();
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(2), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(20), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(50), Price = 200 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(80), Price = 600 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(80), Price = 900 });
PriceLogs.Add(new PriceLog() { LogDateTime = DateTime.Now.AddDays(2), Price = 200 });
//Here is how you can change selected value from ViewModel
SelectedPrice = 900;
// SelectedPriceProlog = PriceLogs[2];
//Or ypu can set
}
public ObservableCollection<PriceLog> PriceLogs { get; set; }
private int selectedPrice ;
public int SelectedPrice
{
get { return SelectedPrice ; }
set
{
selectedPrice = value;
Notify("SelectedPriceProlog");
}
}
<DataGrid ItemsSource="{Binding PriceLogs}" SelectedValue="{Binding SelectedPrice, Mode=TwoWay}" SelectedValuePath="Price">
您可以通过将DataGrid的SelectedItem属性绑定到ViewModel属性来实现,该属性必须是您的DataGrids ItemSource和绑定必须为TwoWay的类型,然后您可以将VewModel中的该属性设置为您的集合中的任何项目。或者您可以使用上面显示的SelectedValue来实现。现在,如果你想从View更改为ViewModel,那么你的绑定模式必须是OneWay 。我希望这会有所帮助。
答案 1 :(得分:0)
您正在寻找一个更新ViewModel但不反之亦然的DataBinding,因此,有一个名为OneWayToSource
的DataBinding模式,例如:<TextBox Text="{Binding TextProperty, Mode=OneWayToSource}"/>
答案 2 :(得分:0)
你有两个解决方案。
IsSelected
属性。然后你应该调整绑定和
通知父虚拟机更新其属性SelectedItem
或
SelectedItems
SelectedItems
在两个方向上工作(VM - > V和V.
- &GT; VM)无需为项目声明IsSelected
属性。ICommand
。每次选择时都会执行此命令
由用户操作更改。该命令的参数是
DataGrid.SelectedItems集合。如果您需要我可以在明天来办公室时分享代码。