Home > other >  WPF binding window title to a checkbox state
WPF binding window title to a checkbox state

Time:02-13

I have a checkbox which looks something like this (have removed many things to make it short) -

<CheckBox IsChecked="{Binding functionABC, Mode=TwoWay}">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="Checked">
         <i:InvokeCommandAction Command="{Binding Path=XYZ}"/>
      </i:EventTrigger>

      <i:EventTrigger EventName="Unchecked">
        <i:InvokeCommandAction Command="{Binding Path=XYZ}"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</CheckBox>

Now, I have to map the window title of app to 2 different values depending on checked or unchecked. I could have done it normally, but there is a trigger set already for both states, and I don't know how to work around it.

CodePudding user response:

Use a Style with a DataTrigger

<!-- !!! remove the Title property from the Window declaration !!! -->

<Window
  ...>

  <Window.Style>
    <Style TargetType="Window">
      <Style.Triggers>
        <DataTrigger Binding="{Binding functionABC}" Value="True">
          <Setter Property="Title" Value="True Title" />
        </DataTrigger>
        <DataTrigger Binding="{Binding functionABC}" Value="False">
          <Setter Property="Title" Value="False Title" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Window.Style>
  ...
</Window>

Update

As thatguy suggested this style can be simplified by

<!-- !!! remove the Title property from the Window declaration !!! -->

<Window
  ...>

  <Window.Style>
    <Style TargetType="Window">
      <Setter Property="Title" Value="False Title" />
      <Style.Triggers>
        <DataTrigger Binding="{Binding functionABC}" Value="True">
          <Setter Property="Title" Value="True Title" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Window.Style>
  ...
</Window>

CodePudding user response:

You can use an special IValueConverter

public class BooleanToCustomConverter : MarkupExtension, IValueConverter
{
    public string? TrueValue { get; set; }
    public string? FalseValue { get; set; }

    public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool b)
            return b ? TrueValue : FalseValue;
        return Binding.DoNothing;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

and use that within your Binding

<Window
  ...
  Title="{Binding functionABC, Mode=OneWay, Converter={local:BooleanToCustomConverter TrueValue='True Value', FalseValue='False Value'}}"
  ...>

  ...

</Window>
  • Related