NullToVisibilityConverter未被选择更改触发

时间:2017-09-07 21:02:54

标签: c# xaml mvvm

我有一个StackPanel,当我在同一个窗口中没有来自ListView的选定项目时,我想隐藏它。目前,当我打开窗口时,没有选定项目并且StackPanel被隐藏,但是当我从ListView中选择某些内容时,不会发生任何更改。

我在ListView中绑定了SelectedItem,如:

<ListView
     MinHeight="0"
     MaxHeight="500"
     Margin="10,10,10,0"
     Background="#e7f5f4"
     BorderThickness="0"
     ItemsSource="{Binding Issues}"
     ScrollViewer.HorizontalScrollBarVisibility="Hidden"
     SelectedItem="{Binding SelectedIssue}"
     SelectionMode="Single">

Where&#34; SelectedIssue&#34;是我的ViewModel中的自定义类属性(我的整个窗口具有相同的DataContext)。我目前正在将StackPanel的Visibility属性绑定为:

<StackPanel
     Grid.Column="1"
     Margin="13,0,0,5"
     VerticalAlignment="Bottom"
     Background="#ebf7f6"
     Orientation="Horizontal"
     Visibility="{Binding SelectedIssue, 
     Converter={StaticResource NullToVisibilityConverter},
     UpdateSourceTrigger=PropertyChanged}">

我的转换器是:

public class NullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value == null ? Visibility.Collapsed : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

我错过了什么?

编辑:这是我的getter / setter

    private Issue _selectedIssue;
    public Issue SelectedIssue
    {
        get { return _selectedIssue; }
        set { Set(ref _selectedIssue, value); }
    }

    public void RaisePropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
    {
        if (Equals(storage, value))
            return false;
        storage = value;
        RaisePropertyChanged(propertyName);
        return true;
    }

1 个答案:

答案 0 :(得分:0)

显然问题是你没有实现INotifyPropertyChanged或者你没有(在SelectedIssue属性设置器中)引发PropertyChanged事件。

但您可以更简单,将StackPanel直接绑定到ListView.SelectedItem

<ListView x:Name="listView"
     MinHeight="0"
     MaxHeight="500"
     Margin="10,10,10,0"
     Background="#e7f5f4"
     BorderThickness="0"
     ItemsSource="{Binding Issues}"
     ScrollViewer.HorizontalScrollBarVisibility="Hidden"
     SelectedItem="{Binding SelectedIssue}"
     SelectionMode="Single">

<StackPanel
     Grid.Column="1"
     Margin="13,0,0,5"
     VerticalAlignment="Bottom"
     Background="#ebf7f6"
     Orientation="Horizontal"
     Visibility="{Binding SelectedItem, ElementName=listView
     Converter={StaticResource NullToVisibilityConverter}" >