【问题标题】:Visibility is not updating when bound to the Count of a Collection via a Value Converter通过值转换器绑定到集合的计数时,可见性不会更新
【发布时间】:2011-09-12 16:09:56
【问题描述】:

我有一个可以同时选择多个项目的 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,但我不知道该怎么做。

【问题讨论】:

    标签: wpf silverlight silverlight-4.0 binding visibility


    【解决方案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}}" />
    

    【讨论】:

      猜你喜欢
      • 2017-12-18
      • 2023-03-05
      • 2012-08-23
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多