将IsEnabled属性绑定到文本块是否包含数据

时间:2010-08-21 11:32:17

标签: silverlight windows-phone-7

我正在为windows phone使用silverlight,我想将按钮的IsEnabled属性绑定到文本块是否包含文本。换句话说,我想在文本块的Text不为空时启用我的按钮,否则禁用。

是否可以使用样式/设置器/触发器或任何其他机制完全在XAML中执行此操作,还是必须编写转换器?

PS:我还在学习Silverlight,.NET等。

1 个答案:

答案 0 :(得分:6)

由于类型不兼容(并且您通常希望避免代码隐藏/依赖属性),“启用字符串的转换器”是此类简单检查的最佳选择。

由于转换器是围绕项目共享的,并且只是XAML中的一个小条目(并且没有对代码隐藏的更改),所以您不应该担心使用转换器... 转换器是您的朋友 :)

开始制作有用的转换器库,因为同样的问题会一次又一次地出现。

以下是执行所需操作的转换器的一些最小代码(无错误检查):

using System;
using System.Windows.Data;

namespace LengthToEnabledTest
{
    public class LengthToEnabledConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string)
            {
                return (value as string).Length > 0;
            }
            throw new NotImplementedException();
        }

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

        #endregion
    }
}

和一些匹配测试XAML(一个带有1个文本框和1个按钮的简单堆栈面板):

<UserControl x:Class="TransitioningContentContolTest.LengthEnabledTest"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:converter="clr-namespace:LengthToEnabledTest"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <UserControl.Resources>
        <converter:LengthToEnabledConverter x:Key="LengthToEnabledConverter"/>
    </UserControl.Resources>
    <StackPanel x:Name="LayoutRoot" Background="White">
        <TextBox x:Name="textBox" />
        <Button Content="Press me" Height="20" IsEnabled="{Binding Text, ElementName=textBox, Converter={StaticResource LengthToEnabledConverter}}"/>
    </StackPanel>
</UserControl>