Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to disable controls(TextBoxes) using MVVM in WPF?

I Have a text box, depending on the text box value i need to enable/disable other text Boxes.I am using MVVM Pattern.

So here's my problem , whenever i enter some text in TextBox1 ,the Setter for TextBox1 is getting fired and i am able to check in if loop ,whether valus exists and i am disabling other text boxes. Now, when there is single value in text box say "9" and i am deleting / Backspacing it the Set event is not getting triggered in order to enable the other Text Boxes.

View:

<TextBox Text = {Binding TextBox1 , UpdateSourceTrigger = PropertyChanged,Mode= TwoWay}/>
<TextBox Text = {Binding TextBox2 , UpdateSourceTrigger = PropertyChanged,Mode= TwoWay}/>
<TextBox Text = {Binding TextBox3 , UpdateSourceTrigger = PropertyChanged,Mode= TwoWay}/>

View Model:

private int_textBox1;
public int TextBox1
{
 get {return _textBox1;}
 set 
   {
     _textBox1= value;
     if(value > 0)
       {
          //Code for Disabling Other Text Boxes (TextBox2 and TextBox3)
       }
      else
       {
          // Code for Enabling Other Text Boxes (TextBox2 and TextBox3)
       }
     NotifyPropertyChanged("TextBox1");
   }
}
like image 910
Ujjwal27 Avatar asked Dec 27 '22 02:12

Ujjwal27


2 Answers

If you are using MVVM pattern, you should create boolean properties, and bind TextBox.IsEnabled property to it. Your boolean properties should raise PropertyChanged event, in order to tell the view (TextBox in your case) that your property was really changed:

public bool IsEnabled1
{
    get { return _isEnabled1; }

    set
    {
        if (_isEnabled1 == value)
        {
            return;
        }

        _isEnabled1 = value;
        RaisePropertyChanged("IsEnabled1");
    }
}

and then in xaml:

<TextBox Text="{Binding TextBox1, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
         IsEnabled="{Binding IsEnabled1}" />

and so on with other TextBoxes

like image 80
stukselbax Avatar answered Jan 29 '23 05:01

stukselbax


first of all, if you set your updatesourcetrigger to Propertychanged - your setter is called when you do anything in your textbox. i check this in a simple testproject. btw do you call OnPropertyChanged in your setter, because its not in your sample code?

if not your binding seems to be broken. so pls check your binding or post some more relevant code.

EDIT:

if you change your type to int? you can do the following xaml

    <TextBox Text="{Binding MyNullableInt, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, TargetNullValue=''}"/>
like image 35
blindmeis Avatar answered Jan 29 '23 04:01

blindmeis