我的c#ComboBox在选择项目后不调用getter.为什么?
本文关键字:调用 getter 为什么 c#ComboBox 选择 项目 我的 | 更新日期: 2023-09-27 18:28:14
我有一个带SelectedItem的组合框。如果我选择一个项目,我的setter会进行一些计算,也许我想将值重置为旧值。不幸的是,我的观点没有得到更新。
我有以下组合框:
<ComboBox BorderThickness="0" VerticalAlignment="Center" Margin="2,0"
DisplayMemberPath="Name"
ItemsSource="{Binding ItemsVS.View}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" >
</ComboBox>
以下是我的ViewModel:的属性
private CollectionViewSource _itemsVS;
public CollectionViewSource ItemsVS
{
get { return _itemsVS; }
set
{
_itemsVS = value;
if(PropertyChanged!=null)
PropertyChanged(this, new PropertyChangedEventArgs("ItemsVS"));
}
}
private ItemViewModel _selectedItem;
public ItemViewModel SelectedItem
{
get
{
// after setting the old value in the setter the getter is not called
// and the view is not refreshed
return _selectedItem;
}
set
{
var old = _selectedItem;
_selectedItem = value;
// After some logic I want to have the old value!!!!!!!!!!!!!!
_selectedItem = old;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
}
}
如果您想让ComboBox
在设置新值后读回当前值,您需要在Binding
中添加一个"无操作"Converter
,它实际上什么都不做。这是一个有用的小技巧,因为绑定通常不会检查实际应用的源值是否与绑定提供的新值匹配。添加转换器会强制进行检查。
public sealed class NoOpConverter : IValueConverter
{
public static readonly NoOpConverter Instance = new NoOpConverter();
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return value;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
return value;
}
}
<ComboBox SelectedItem="{Binding Path=SelectedItem,
Mode=TwoWay,
Converter={x:Static NoOpConverter.Instance}}"
... />