选择项目后,我的c#ComboBox不会调用getter。为什么?

时间:2014-10-29 15:35:37

标签: c# wpf binding combobox

我有一个带有SelectedItem的Combobox。如果我选择一个项目,我的setter会进行一些计算,也许我想将值重置为旧值。不幸的是,我的观点没有刷新。

我有以下ComboBox:

<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"));


    }
}

1 个答案:

答案 0 :(得分:2)

如果您想在设置新值后让ComboBox读回当前值,则需要添加&#34; no op&#34;对Converter Binding有效无效的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}}"
          ... />
{{1}}