My c# ComboBox does not call the getter after selecting an item. Why?

懵懂的女人 提交于 2019-12-24 01:39:59

问题


I have an Combobox with SelectedItem. If I select an item my setter does some calculation and perhaps I want to reset the value to the old one. Unfortunatly my view does no refresh.

I have the following ComboBox :

<ComboBox BorderThickness="0" VerticalAlignment="Center" Margin="2,0"
  DisplayMemberPath="Name" 
  ItemsSource="{Binding ItemsVS.View}" 
  SelectedItem="{Binding SelectedItem, Mode=TwoWay}" >

</ComboBox>

Here are the properties of my 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:


If you want to make the ComboBox read back the current value after setting the new value, you need to add a "no op" Converter to your Binding that effectively does nothing. It's a useful little trick, as a binding will not normally check to see whether the source value actually applied matches the new value provided by the binding. Adding a converter forces it to check.

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}}"
          ... />


来源:https://stackoverflow.com/questions/26634526/my-c-sharp-combobox-does-not-call-the-getter-after-selecting-an-item-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!