fanarek
fanarek

Reputation: 367

How to use PropertyChanged instead of TextBox TextChanged event in WPF?

Is it possible to use PropertyChanged instead of TextChanged on TextBox in WPF ? How to know if PropertyChanged triggered or not ?

I have TextBox like this:

 <TextBox x:Name="kodpTxt" Text="{Binding Selected.KodP,UpdateSourceTrigger=PropertyChanged}" Width="75" Margin="84,55,0,0" />

I would prefer to avoid TextChanged event, because I change kodpTxt binding from database and it's length is not always same, so I can't check if kodpTxt.Text.Length >= 5 etc.

I was looking for alternative and realized that maybe I can do something with PropertyChanged but I don't know how to find out when PropertyChanged happened.

private string _kodp;

public string KodP
{
    get { return _kodp; }
    set
    {
        _kodp = value;
        OnPropertyChanged("KodP");
    }
}
public void OnPropertyChanged(string name)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}

public event PropertyChangedEventHandler PropertyChanged;

To visualise my problem I will describe it a little:

I have ViewModel and UserControl with kodpTxt TextBox. In UserControl I set up Selected.XYZ propierties. Onfurtunetly I can't manipulate UserControl controls from ViewModel. That's why I'm looking for something like:

public void kodpTxt_PropertyChanged()
{
    //Do Something (get data from SqlServer and pass them to some UserControl controls
}

Description

Can you explain that ?

Upvotes: 0

Views: 1998

Answers (2)

Thomas Flinkow
Thomas Flinkow

Reputation: 5115

As Alexy has already said use Mode.TwoWay in the binding so that you can perform your checks in the property setter like this:

public string KodP
{
    get { return ... }
    set
    {
        if(value.Length >= 5)
        {
            ...
        }

        // Set the value to your field / database etc.
    }
}

Using this method, there is no need for any event to be called, since you can do the check / invoke methods etc. in the property setter directly.

Upvotes: 1

Oleksii Klipilin
Oleksii Klipilin

Reputation: 1936

Use Mode=TwoWay

<TextBox x:Name="kodpTxt" Text="{Binding Selected.KodP, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="75" Margin="84,55,0,0" />

And you will get invoked setter for Selected.KodP property. That's how you can get this event.

Upvotes: 2

Related Questions