WPF 将 window 标题绑定到复选框状态

WPF binding window title to a checkbox state

我有一个看起来像这样的复选框(删除了很​​多东西以使其简短)-

<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>

现在,我必须根据选中或未选中将应用程序的 window 标题映射到 2 个不同的值。我本来可以正常完成的,但是已经为这两种状态设置了触发器,我不知道如何解决它。

使用 StyleDataTrigger

<!-- !!! 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>

更新

正如所建议的那样,这种风格可以通过

来简化
<!-- !!! 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>

sample project on github

你可以使用特殊的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;
    }
}

并在您的绑定中使用它

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

  ...

</Window>

sample project on github