通过值转换器绑定到集合的计数时,可见性不会更新

时间:2011-06-10 16:58:21

标签: wpf silverlight silverlight-4.0 binding visibility

我有一个ListBox,可以一次选择多个项目。如果只选择了ListBox中的一个项目,我有一个需要可见的UserControl。

以下是需要隐藏的窗格:

<views:WebMethodsPane x:Name="WebMethodsPane"  Grid.Column="1" Grid.Row="0"   Margin="5,5,5,0" 
Visibility="{Binding SelectedList, Converter={StaticResource SelectionToVisibilityConverter}}" />

SelectedList对象是一个ObservableCollection,它填充了用户在ListBox中选择的项目。 (我使用了一种行为来做这件事。)

SelectionToVisibilityConverter如下:

public class SelectionToVisibilityConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var selectedServices = value as ObservableCollection<WebService>;
        return (selectedServices.Count == 1 ? Visibility.Visible : Visibility.Collapsed);
    }

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

当我运行应用程序时,窗格被隐藏并保持隐藏状态。当我从ListBox中选择不同数量的项目时,可见性不会更新。如何确保可见性更新?也许我需要使用INotifyPropertyChanged,但我不确切知道如何使用。

1 个答案:

答案 0 :(得分:1)

我将采用的方法是向绑定对象添加一个新属性,即SingleItemSelected布尔属性。

以下内容: -

 public class YourClass : INotifyPropertyChanged
 {

     public ObservableCollection<WebService> SelectedList {get; private set; }

     // ctor
     public YourClass()
     {
         SelectedList = new ObservableCollection<WebService>();
         SelectedList.CollectionChanged += SelectedList_CollectionChanged;
     }

     private void SelectedList_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
     {
         SingleItemSelected = SelectedList.Count == 1;
     }

     private bool mySingleItemSelected
     public bool SingleItemSelected
     {
         get { return mySingleItemSelected; }
         private set
         {
              if (mySingleItemSelected != value)
              {
                   mySingleItemSelected = value;
                   PropertyChanged(this, new PropertyChangedEventArgs("SingleItemSelected"));
              }
         }
     }

     public event PropertyChangedEventHandler PropertyChanged = delegate {};

}

所以现在你需要的是一个简单的BoolToVisibilityConverter,有很多这样的例子,我更喜欢我自己的here

然后你xaml(假设你在资源中放置了一个转换器的实例,并带有“BtoV”键):

<views:WebMethodsPane x:Name="WebMethodsPane"  Grid.Column="1" Grid.Row="0" Margin="5,5,5,0"
    Visibility="{Binding SingleItemSelected, Converter={StaticResource BtoV}}" />