Search code examples
c#wpfxamlwinapp

TextBox isEnabled binding dependant on combobox item


So i have a ComboBox bound to a list of items. { A,B,C,D,E }

<ComboBox x:Name="cmbDMS" ItemsSource="{Binding Types}" SelectedValue="{Binding Type,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="top" Width="120" SelectionChanged="cmbDMS_SelectionChanged" />

also a TextBox.

<TextBox IsEnabled="{Binding isTypeB}" Grid.Row="6" Width="250" Margin="0,2" />

I cannot figure out how to update the TextBox isEnabled property once the ComboBox SelectedValue has changed to B. It works once i exit and come back into the view but i want it to be instant.

Thanks.


Solution

  • I have had some problems in the past with binding to SelectedValue and it properly raising events. Unless you have an explicit reason, I like to bind to the SelectedItem

    The issue i have found with this operation, is that the binding to the bool object will not necessarily get updated via the changing of the SelectedItem of the ComboBox

    If you would like the two to be linked, an easy way to do this is to raise the Property changed event for the bool isTypeB property within the setter of the "Type" propery:

    (as i dont know the Type of "Type" i will assume it is a string):

    public string Type
    {
      get{...}
      set
      {
        //...set logic
        RaisePropertyChanged(); //will notify when "Type" changes
        RaisePropertyChanged("isTypeB"); //will notify that isTypeB is changed
      }
    }
    ...
    public bool isTypeB => Type == "TypeB";
    

    Reference for RaisePropertyChanged:

        public event PropertyChangedEventHandler PropertyChanged;
    
        public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }