How to set a control property based on another control property in wpf

I have a scenario where based on the text value of a textbox I have to disable and enable the say button, for TextBox.Text = "abc" or "cdf" the button should be disabled and for other values ​​it should be enabled.

this should only be written in Xaml.

Thanks in advance

+2


source to share


2 answers


It looks like you can use triggers for this:

The button turns off when an ABC value is entered into the text box, and then turns on when the value changes to something other than 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>

      

+7


source


This cannot be done strictly in XAML, and such a requirement does not make sense. This is the business logic that should manifest itself in the view model:

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"; }
    }
}

      



Then in your XAML:

<TextBox Text="{Binding Text}"/>
<Button IsEnabled="{Binding IsButtonEnabled}"/>

      

+2


source







All Articles