B.Balamanigandan
B.Balamanigandan

Reputation: 4875

How to Bind Property from a VIew Model to DataTrigger Setter Based on Condition?

I'm having a TextBox, if the TextBox has the Text.Length >0 then I have to change the HasChar property True otherwise False. Here I can't able to Bind the Property in the Setter.

The XAML Source Code:

<TextBox Text="WPF">
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Value="0"
                    Binding="{Binding Text.Length, RelativeSource={RelativeSource Self}}">
                    <Setter Property="{Binding HasChar}" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

The View Model C# Source Code :

private bool _hasChar= true;
public bool HasChar
{
    get { return _hasChar; }
    set
    {
        _hasChar= value;
        OnPropertyChanged();
    }
}

Upvotes: 1

Views: 1078

Answers (2)

Dhruv Panchal
Dhruv Panchal

Reputation: 60

You can not bind a property in the setter. Style is used to set the UI element properties like Text,Visibility,Foreground etc.

Upvotes: 1

Dennis
Dennis

Reputation: 37790

You're misusing triggers.
The right way to go:

1) XAML:

<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"/>

2) view model. You don't need to add setter to HasChar. If this property is bound to something in view, just raise appropriate PropertyChanged:

public class ViewModel : INotifyPropertyChanged
{
    // INPC implementation is omitted

    public string Text
    {
        get { return text; }
        set
        {
            if (text != value)
            {
                text = value;
                OnPropertyChanged();                    
                OnPropertyChanged("HasChar");
            }
        }
    }
    private string text;

    public bool HasChar
    {
        get { return !string.IsNullOrEmpty(Text); }
    }
}

Upvotes: 3

Related Questions