c# - WPF 绑定(bind) : ! 值

标签 c# wpf binding

<分区>

我有按钮:

<Button Content="Stop loading" />

在 ViewModel 中,我有属性 IsLoaded。我不想编写属性 IsNotLoaded 但我想在绑定(bind)中使用 IsLoaded 并在 IsLoaded = true 时禁用按钮。

如何实现这样的东西:

<Button Content="Stop loading" IsEnabled="{Binding !IsLoaded}" />

附言如果它比编写附加属性更困难,我将使用 IsNotLoaded 属性。

最佳答案

这样做的标准方法是制作一个 IValueConverter这将反转你的 bool 值。虽然创建此类比添加新属性更困难,但它是完全可重用的 - 因此稍后,您可以在其他绑定(bind)中重用它(不会用大量 !Property 属性污染您的 ViewModel)。

这个类看起来像这样:

[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool booleanValue = (bool)value;
        return !booleanValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool booleanValue = (bool)value;
        return !booleanValue;
    }
}

然后,您可以将其添加到您的资源中:

<src:InvertBoolConverter x:Key="invertBoolConverter"/>

一旦你有了这个,你会像这样使用它:

<Button Content="Stop loading" 
        IsEnabled="{Binding IsLoaded, Converter={StaticResource invertBoolConverter}}" 
/>

关于c# - WPF 绑定(bind) : ! 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4830563/

相关文章:

c# - 有没有办法获取对话框的取消事件

C# - 找到重复键时选择两个值中的最小值

c# - Universal App中的NavigationSevice

css - 如何将 bind-attr 类附加到 Ember 中的初始类?

c# - MVVM INotifyPropertyChanged 与基类 PropertyChange 冲突

c# - Stripe Payments - 如何更改订阅计划并立即收费?

c# - 超时 Web Api 请求?

wpf - 在 Visual Studio 设计器中隐藏 WPF 元素

c# - 在流文档中跨列跨文本

wpf - DataTemplate 绑定(bind)取决于属性类型和工作属性绑定(bind)