4

ウィンドウのコードビハインドは、依存関係プロパティ「アクティブ」を定義しています...

public partial class MainWindow : Window
{
  public MainWindow() { InitializeComponent(); }

  public bool Active
  {
     get { return (bool) GetValue(ActiveProperty); }
     set { SetValue(ActiveProperty, value); }
  }
  public static readonly DependencyProperty ActiveProperty =
      DependencyProperty.Register("Active", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false));
}

次に、xaml で 2 つのチェックボックスを使用してそのプロパティにバインドします。また、そのプロパティに基づいて四角形の塗りつぶしを変更したいと考えています。どうすればこれを機能させることができますか?

<Window x:Class="WpfTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="350"
        Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <StackPanel>
    <CheckBox IsChecked="{Binding Active}" />
    <CheckBox IsChecked="{Binding Active}" />
    <Rectangle Fill="Gray"
               Width="50"
               Height="50">
      <Rectangle.Style>
        <Style TargetType="Rectangle">
          <Style.Triggers>
            <DataTrigger Binding="{Binding Active}"
                         Value="True">
              <Setter Property="Fill"
                      Value="Green" />
            </DataTrigger>
          </Style.Triggers>
        </Style>
      </Rectangle.Style>
    </Rectangle>
  </StackPanel>
</Window>

1 つのボックスをチェックすると、もう 1 つのボックスが自動的にチェックされますが、長方形の色は変更されません :(

4

2 に答える 2

3

プロパティを設定すると、スタイルによってこのプロパティで定義されたトリガーは機能しなくなります。別の dataTrigger を定義して、False 値の背景を変更できます。

  <StackPanel>
        <CheckBox IsChecked="{Binding Active}"/>
        <CheckBox IsChecked="{Binding Active}"/>
        <Rectangle Width="50" Height="50">
            <Rectangle.Style>
                <Style TargetType="Rectangle">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Active}" Value="True">
                            <Setter Property="Fill" Value="Green"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Active}" Value="false">
                            <Setter Property="Fill" Value="Gray"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Rectangle.Style>
        </Rectangle>
    </StackPanel>
于 2013-04-21T12:50:41.670 に答える