如何根据wpf中其他控件的属性设置控件的属性

时间:2009-08-26 10:30:58

标签: wpf xaml

我有一个场景,根据文本框的文本值,我必须禁用并启用按钮说, 对于TextBox.Text =“abc”或“cdf”,应禁用该按钮,对于其他值,应启用该按钮。

这必须只在Xaml中编写。

提前致谢

2 个答案:

答案 0 :(得分:7)

看起来您可以使用触发器执行此操作:

当在文本框中输入值ABC时,按钮被禁用,然后在值变为ABC之外的其他值时启用。

<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">

<Window.Resources>
    <Style x:Key="disableButton" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding ElementName=textBox1,Path=Text}" Value="ABC">
                <Setter Property="IsEnabled" Value="False" />
            </DataTrigger>

        </Style.Triggers>
    </Style>
</Window.Resources>

<StackPanel>
    <TextBox x:Name="textBox1"/>
    <Button Style="{StaticResource disableButton}" Height="23" Name="button1" Width="75">Button</Button>
</StackPanel>

答案 1 :(得分:2)

这在XAML中不可能严格执行,这样的要求也没有意义。这是应该在视图模型中表现出来的业务逻辑:

public class MyViewModel : ViewModel
{
    private string _text;

    public string Text
    {
        get { return _text; }
        set
        {
            if (_text != value)
            {
                _text = value;
                OnPropertyChanged("Text");
                OnPropertyChanged("IsButtonEnabled");
            }
        }
    }

    public bool IsButtonEnabled
    {
        get { return _text != "abc"; }
    }
}

然后,在你的XAML中:

<TextBox Text="{Binding Text}"/>
<Button IsEnabled="{Binding IsButtonEnabled}"/>
相关问题