WPF で逆ブールプロパティをバインドする方法は? 質問する

WPF で逆ブールプロパティをバインドする方法は? 質問する

私が持っているのは、プロパティを持つオブジェクトです。このプロパティが true の場合、ボタン (例) のプロパティを false にIsReadOnly設定したいと思います。IsEnabled

同じように簡単にできると信じたいのですIsEnabled="{Binding Path=!IsReadOnly}"が、WPF ではそうはいきません。

すべてのスタイル設定をやらなければならないのでしょうか? あるブール値を別のブール値の逆数に設定するという単純な操作なのに、言葉が多すぎるように思えます。

<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>

ベストアンサー1

bool プロパティを反転する ValueConverter を使用できます。

: : 翻訳:

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
    }

おすすめ記事