WPF 多绑定和转化器

来源:互联网 发布:迷你小钢炮淘宝地址 编辑:程序博客网 时间:2024/06/06 02:16


将两个 textBox 的Text属性绑定到 Button的IsEnabled

如果text为空则Button不可用


<Window x:Class="MultiBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:loc="clr-namespace:MultiBinding"
        Title="MainWindow" Height="350" Width="525"      
        >
    <Window.Resources>
        <loc:StringBooleanConverter x:Key="StringBooleanConverter"/>
    </Window.Resources>
    <Grid>
        <TextBox Name="txt1" HorizontalAlignment="Left" Height="23" Margin="126,80,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
        <TextBox Name="txt2" HorizontalAlignment="Left" Height="23" Margin="126,117,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="120"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="126,174,0,0" VerticalAlignment="Top" Width="75">
            <Button.IsEnabled>
                <MultiBinding Converter="{StaticResource StringBooleanConverter}">
                    <Binding ElementName="txt1" Path="Text"/>
                    <Binding ElementName="txt2" Path="Text"/>
                </MultiBinding>
            </Button.IsEnabled>
        </Button>
    </Grid>
</Window>



namespace MultiBinding
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class StringBooleanConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool flag = true;
            foreach (object value in values)
            {
                string str = value as string;
                if (str == string.Empty)
                {
                    flag= false;
                    break;
                }
            }
            return flag;
        }


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


}

0 0