tags:

views:

60

answers:

1

I have a .xaml file and a .cs file that share value with Binding.

To make it simples, I have 1 button and 1 textbox. I want to button to be disabled when the textbox's text has no character.

Here is the two codes of the xaml for binding:

  <TextBox Name="txtSend" Text="{Binding Path=CurrentText,UpdateSourceTrigger=PropertyChanged}"></TextBox>
    <Button IsEnabled="{Binding Path=IsTextValid}"  Name="btnSend">Send</Button>

The two properties in the .cs file look like that:

    public string CurrentText
    {
        get
        {
            return this.currentText;
        }
        set
        {
            this.currentText = value;
            this.PropertyChange("CurrentText");
            this.PropertyChange("IsTextValid");
        }
    }

    public bool IsTextValid
    {
        get
        {
            return this.CurrentText.Length > 0;
        }
    }

The this.PropertyChanged is simply a method that call PropertyChanged from INotifyPropertyChanged.

The problem is that I have to call the this.PropertyChange("IsTextValid"); in the Setter of the CurrentText to be able to have the button state change.

Question 1) Is it the good way to do it... if the rules become more complexe I might require to call a lot of PropertyChanged...?

Question 2) My button is enable when the form load. How can I make it check the method from the start?

+1  A: 

Question 1: This is correct. There is no problem doing that. However you could take a look at the validation using the IDataErrorInfo. (Google search for it, and you will find a lot of good examples)

Question 2: make sure your "currentText" string is initialized with string.empty. Because if you did not initialized it, it will be null, and the getter for IsTextValid will throw an exception, and WPF will fail to retrieve the value.

Or do it like that:

public bool IsTextValid
{
    get
    {
        return ! string.IsNullOrEmpty( this.CurrentText );
    }
}
decasteljau
+1 and Answer accepted :) +25 reps for you my friend. Thank you.
Daok