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

How to bind a Button's IsEnabled member to a TextBox's content?

我有一个比较标准的设置:根据一个TextBox的内容是否为空,我想enable/disable一个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 属性.

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


1) 完整错误输出:

Error: BindingExpression path error: 'Length' property not found on 'Windows.Foundation.IReference`1<String>'. BindingExpression: Path='Text.Length' DataItem='Windows.UI.Xaml.Controls.TextBox'; target element is 'Windows.UI.Xaml.Controls.Button' (Name='null'); target property is 'IsEnabled' (type 'Boolean')

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

您需要创建一个转换器,其中 return 是一个布尔值,其值是真还是假取决于整数的值。在你的情况下,我假设你想要一个零到 return false 的长度和一个大于零到 return true 的长度。如果在 c++/cx Length 中不是 属性 而是一种方法(与 C# 不同),那么您将无法直接绑定到它。您将必须绑定文本 属性,然后在转换器中调用 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();
    }
};

然后在您的绑定中添加转换器并将路径更改为仅文本:

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

转换器在 XAML 中声明如下:

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