我拥有的是一个具有IsReadOnly属性的对象。如果此属性为true,我想将按钮上的IsEnabled属性设置为false(例如)。

我愿意相信我可以像IsEnabled="{绑定路径=!IsReadOnly}”,但这与WPF不兼容。

我是否不得不经历所有的样式设置?对于将一个bool值设置为另一个bool值的倒数这样简单的事情来说,似乎太啰嗦了。

<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Path=IsReadOnly}" Value="True">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>
            <DataTrigger Binding="{Binding Path=IsReadOnly}" Value="False">
                <Setter Property="IsEnabled" Value="True" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Button.Style>

当前回答

在视图模型中再添加一个属性,它将返回反向值。 然后把它绑定到按钮上。 像;

视图模型:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

在xaml:

IsEnabled="{Binding IsNotReadOnly"}

其他回答

类似于jevansio的回答,实现了一个名为BindableBool的类,具有isstrue和IsFalse属性,我可以将两个替代组件的IsVisible绑定到。

Github: https://github.com/balintn22/BindableBool

努格特:是的。可绑定布尔

我使用类似于@Ofaim的方法

private bool jobSaved = true;
private bool JobSaved    
{ 
    get => jobSaved; 
    set
    {
        if (value == jobSaved) return;
        jobSaved = value;

        OnPropertyChanged();
        OnPropertyChanged("EnableSaveButton");
    }
}

public bool EnableSaveButton => !jobSaved;

你可以使用ValueConverter来反转bool属性。

XAML:

IsEnabled="{Binding Path=IsReadOnly, Converter={StaticResource InverseBooleanConverter}}"

转换器:

[ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter: IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new InvalidOperationException("The target must be a boolean");

            return !(bool)value;
        }

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

        #endregion
    }

在视图模型中再添加一个属性,它将返回反向值。 然后把它绑定到按钮上。 像;

视图模型:

public bool IsNotReadOnly{get{return !IsReadOnly;}}

在xaml:

IsEnabled="{Binding IsNotReadOnly"}

你考虑过IsNotReadOnly属性吗?如果被绑定的对象是MVVM域中的ViewModel,那么附加属性非常有意义。如果它是一个直接的实体模型,您可能会考虑组合并将实体的专用ViewModel呈现给表单。