WPF C# 中的绑定可见性转换器

man*_*der 5 c# wpf xaml binding converters

我有一个集合类型的依赖属性,当它的回调根据计数触发时,我需要设置屏幕上某些控件的可见性。

但控件始终处于折叠状态。根据代码,一个控件始终保持可见。

XAML 绑定是

   <TextBlock Text="106 search results for 'a'" Margin="5,0,100,0" Visibility="{Binding CountLabelVisibleReverse, Converter={StaticResource VisibilityConverter}}"/>
 <StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,0,90,0"  
                            Visibility="{Binding CountLabelVisible, Converter={StaticResource VisibilityConverter}}">
 <TextBlock Text="Sort By"  />
 <ComboBox Style="{StaticResource ComboBoxStyle1}" Width="100" x:Name="ComboBoxSorting" ItemsSource="{Binding SortBy}" />
   </StackPanel>
Run Code Online (Sandbox Code Playgroud)

我的两个属性是

    public bool CountLabelVisible { get; set; }

    public bool CountLabelVisibleReverse { get; set; }
Run Code Online (Sandbox Code Playgroud)

依赖属性回调

   private static void ItemsCollectionChanged(DependencyObject obj, DependencyPropertyChangedEventArgs eventArgs)
    {
        var listingUserControl = (obj as ListingUserControl);

        var itemsResult = (eventArgs.NewValue as List<ItemsResult>);
        if (listingUserControl != null && itemsResult != null)
        {
            listingUserControl.CountLabelVisible = itemsResult.Count > 0;
            listingUserControl.CountLabelVisibleReverse =itemsResult.Count <= 0;
        }
    }
Run Code Online (Sandbox Code Playgroud)

转换器代码是

 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (parameter == null)
            return (bool)value == false ? Visibility.Collapsed : Visibility.Visible;

        return (bool)value ? Visibility.Collapsed : Visibility.Visible;
    }
Run Code Online (Sandbox Code Playgroud)

slu*_*ter 5

您犯了一个经典错误,即绑定到对绑定有效的自动属性,但在更改时不通知,这意味着绑定子系统无法检测更改并更新绑定目标。

要解决此问题,请在视图模型上实现INotifyPropertyChanged,然后确保从属性通知属性更改。

例如,我的视图模型的基类中有以下内容:

public abstract class BaseViewModel : INotifyPropertyChanged
{

    /// <summary>
    /// Helper method to set the value of a property and notify if the value has changed.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="newValue">The value to set the property to.</param>
    /// <param name="currentValue">The current value of the property.</param>
    /// <param name="notify">Flag indicating whether there should be notification if the value has changed.</param>
    /// <param name="notifications">The property names to notify that have been changed.</param>
    protected bool SetProperty<T>(ref T newValue, ref T currentValue, bool notify, params string[] notifications)
    {
        if (EqualityComparer<T>.Default.Equals(newValue, currentValue))
            return false;

        currentValue = newValue;
        if (notify && notifications.Length > 0)
            foreach (string propertyName in notifications)
                OnPropertyChanged(propertyName);

        return true;
    }

    /// <summary>
    /// Raises the <see cref="E:PropertyChanged"/> event.
    /// </summary>
    /// <param name="propertyName">The name of the property that changed.</param>
    protected void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    /// <summary>
    /// Occurs when a property value changes.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

}
Run Code Online (Sandbox Code Playgroud)

然后在你的常规视图模型中:

public class MyViewModel : BaseViewModel
{
    private bool _countLabelVisible;

    public bool CountLabelVisible
    {
        get { return _countLabelVisible; }
        set { SetProperty(ref value, ref _countLabelVisible, true, "CountLabelVisible", "CountLabelVisibleReverse"); }
    }

    public bool CountLabelVisibleReverse { get { return !_countLabelVisible; }} 
}
Run Code Online (Sandbox Code Playgroud)

这样,当CountLabelVisiblegets 改变时,它也会通知 property CountLabelVisibleReverse,并且该 propertyCountLabelVisibleReverse仅包含一个 getter - 因为它始终是 的倒数CountLabelVisible

这样就可以按照您拥有的方式修复您的代码,但现实是您不需要保留该CountLabelVisibleReverse属性,相反您可以:

  • 创建一个反向可见性转换器作为单独的转换器
  • 通过在绑定上传递可选参数来创建多功能可见性转换器
  • 堆叠多个转换器,其中一个转换器的输出通过管道传输到下一个转换器的输入