从字符串绑定 IsEnabled 值

lex*_*Roy 0 wpf binding textbox wpf-controls isenabled

如何将字符串值绑定YNisEnabled 值?

<TextBox IsEnabled="{Binding Path=StringValueFromSomeEntity, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
Run Code Online (Sandbox Code Playgroud)

StringValueFromSomeEntity 可以是一个YN值。

Flo*_* Gl 5

使用转换器将字符串转换为布尔值:

public class StringToBoolConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value.ToString().ToLower() == "y")
           return true;
        return false;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if ((bool)value)
           return "Y";
        return "N";
    }
}
Run Code Online (Sandbox Code Playgroud)

参考资源中的内容:

<Window.Resources>
    <conv:StringToBoolConverter x:Key="StringToBool"/>
</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

将其应用于您的绑定(如果您只想根据字符串更改 IsEnabled 属性,请使用 Mode=OneWay,但如果您确实想绑定 TwoWay,则需要 ConvertBack 方法):

<TextBox IsEnabled="{Binding Path=StringValueFromSomeEntity, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ResourceKey=StringToBool}"/>
Run Code Online (Sandbox Code Playgroud)