如何将Button的IsEnabled成员绑定到TextBox的内容?

时间:2016-06-04 19:12:27

标签: xaml windows-phone-8 windows-runtime winrt-xaml c++-cx

我有一个相当标准的设置:根据TextBox的内容是否为空,我想启用/禁用Button控件。

我试过,在WPF应用程序中可以使用什么,但在Windows运行时运行时不会产生所需的行为:

<StackPanel>
    <TextBox x:Name="ItemNameTextBox" Header="Item" />
    <Button Content="Add Item"
            IsEnabled="{Binding ElementName=ItemNameTextBox,
                                Path=Text.Length,
                                Mode=OneWay}" />
</StackPanel>

然而,在运行时,这会产生以下调试输出 1)

Error: BindingExpression path error: 'Length' property not found on 'Windows.Foundation.IReference`1<String>'.

错误消息是正确的:Windows::Foundation::IReference<String>没有Length属性。

问题:如何将IsEnabled的{​​{1}}属性绑定到Button的文本长度属性?我是否必须实现自定义数据转换器,或者只能使用标记来完成?

<小时/> 1) 完整错误输出:

TextBox

1 个答案:

答案 0 :(得分:2)

您不能将布尔值绑定到整数。

您需要创建一个转换器,该转换器返回一个值为true或false的布尔值,具体取决于整数的值。在您的情况下,我假设您希望长度为零以返回false并且长度大于零以返回true。如果在c ++ / cx中,Length不是属性而是方法(与C#不同),那么你将无法直接绑定它。您将必须绑定Text属性,然后在转换器中调用Length方法:

public ref class LengthToIsEnabledConverter sealed : public Windows::UI::Xaml::Data::IValueConverter
{
public:
    virtual Platform::Object^ Convert( Platform::Object^ value,
                                       Windows::UI::Xaml::Interop::TypeName targetType,
                                       Platform::Object^ parameter,
                                       Platform::String^ language ) {
        Platform::String^ text = safe_cast<Platform::String^>( value );
        return ( text->Length() > 0 );
    }

    virtual Platform::Object^ ConvertBack( Platform::Object^ value,
                                           Windows::UI::Xaml::Interop::TypeName targetType,
                                           Platform::Object^ parameter,
                                           Platform::String^ language ) {
        throw ref new Platform::NotImplementedException();
    }
};

然后在绑定中添加转换器并将路径更改为Text:

IsEnabled="{Binding ElementName=ItemNameTextBox,
                    Path=Text,
                    Mode=OneWay,
                    Converter={StaticResource LengthToIsEnabledConverter}" />

转换器在XAML中声明如下:

<UserControl.Resources>
    <converters:LengthToIsEnabledConverter x:Key="LengthToIsEnabledConverter " />
</UserControl.Resources>