gpt4 book ai didi

c# - 当值在源的 set 子句中被检查为无效时更新目标

转载 作者:行者123 更新时间:2023-12-03 10:44:46 24 4
gpt4 key购买 nike

我在 WPF 中使用 MVVM。

我尝试将 ListView 的 SelectedIndex 绑定(bind)到具有 TwoWay 模式的 View 模型,代码如下:

XAML:

<ListView  SelectedIndex="{Binding Path=CurrentIndex, Mode=TwoWay>
...
</ListView>

View 模型:
public DemoViewModel : INotifyPropertyChanged
{
...
public int CurrentIndex
{
get
{
return _currentIndex;
}
set
{
if (value == _currentIndex)
return;
try
{
DoSomething(value);
}
catch(DataInvalidException e)
{
OnPropertyChanged("CurrentIndex");
MessageBox.Show(e.message);
return;
}

_currentIndex = value;
OnPropertyChanged("CurrentIndex");
}
}
}
int _currentIndex;
}

它几乎可以工作,但是当它捕获 DataInvalidException 并返回时,我希望将 SelectedIndex 保持为其旧值。所以我调用 OnPropertyChanged()不更新 _currentIndex , 这样绑定(bind)目标 ListView.SelectedIndex应该改回原来的值。但它没有。

任何帮助将不胜感激,并原谅我半生不熟的英语。

最佳答案

将带有 ItemsSource 的 ListView 绑定(bind)到 VM 中的 ObervableCollection/CollectionView 并将 SelectedItem 绑定(bind)到 VM 中的 DataTypeSelectedItem 属性。

例如 View :

 <ListView Name="ListViewWithCustomItems" 
SelectedItem="{Binding SelectedCustomItem}"
SelectionMode="Single"
ItemsSource="{Binding CustomItems}">

View 模型
public ObservableCollection<CustomItem> CustomItems
{
get { return _customItems; }
private set
{
if (Equals(value, _customItems)) return;
_customItems= value;
RaisePropertyChanged("CustomItems");
}
}

public CustomItem SelectedCustomItem
{
get { return _selectedCustomItem }
private set
{
if (Equals(value, _selectedCustomItem )) return;
try
{
DoSomething(value);
//if you need the index and not the model do one way-Binding to the index too
}
catch(DataInvalidException e)
{
MessageBox.Show(e.message);
return;
}
_selectedCustomItem = value;
RaisePropertyChanged("SelectedCustomItem");
}
}

关于c# - 当值在源的 set 子句中被检查为无效时更新目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com