Search code examples
wpfdata-bindingdevexpresswpf-controls

Changing a property controller based on other controller's property value in wpf


Consider in my wpf application, I have a checkbox and 2 textedits, as below:

<CheckBox x:Uid="Checkbox_1" FlowDirection="RightToLeft" IsChecked="{Binding TickCheckBox, Mode=TwoWay}" Style="{StaticResource StandardCheckBoxStyle}">My Checkbox</CheckBox>

<dxe:TextEdit x:Uid="dxe:TextEdit_1" Grid.Row="1" Grid.Column="1" Width="100" Style="{StaticResource FleetScheduledHoursStyle}" EditValue="{Binding RealValue, Mode=OneWay}" EditMode="InplaceInactive" ToolTipService.ShowDuration="20000" />

<dxe:TextEdit x:Uid="dxe:TextEdit_2" Grid.Row="1" Grid.Column="1" Width="100" Style="{StaticResource FleetScheduledHoursStyle}" EditValue="{Binding RealValue, Mode=OneWay}" EditMode="InplaceInactive" ToolTipService.ShowDuration="20000" />

The TickCheckBox is bound to a property in my viewmodel as below:

private bool tickCheckBox;
public bool TickCheckBox
{
    get
    {
        return this.tickCheckBox;
    }
    set
    {
        if (this.TickCheckBox.Equals(value))
        {
               return;
        }
        this.tiketCheckBox = value;
        this.NotifyPropertyChange(() => this.TickCheckBox);
    }
}

How do I change the property "EditMode" of one of the textedit (say Text_Edit1) to "InplaceActive" when I ticked the checkbox?

Thanks for your help!


Solution

  • You can use an IValueConverter:

    BoolToEditModeConverte.cs

    public class BoolToEditModeConverter : IValueConverter
    {
      public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        if (!(value is bool isChecked))
        {
          throw new ArgumentException("Converter value must be of type 'bool'");
        }
        return isChecked 
          ? EditMode.InplaceInactive
          : EditMode.None;
      }
    
      public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      {
        throw new NotSupportedException();
      }
    }
    

    Usage

    <Window>
      <Window.Resources>
        <BoolToEditModeConverte x:Key="BoolToEditModeConverte" />
      </Window.Resources>
    
      <CheckBox x:Name="MyCheckbox" />
    
      <TextEdit EditMode="{Binding ElementName=MyCheckBox, 
                                   Path=IsChecked, 
                                   Converter={StaticResource BoolToEditModeConverte}}" />
    </Window>