私は2つだけのTextBlockの存在のUserControlを持っている:文字列の値が等しくない場合、TextBlockの背景色を変更するにはどうすればよいですか?
<UserControl [...] x:Name="root">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Text1, ElementName=root}" />
<TextBlock Text="{Binding Text2, ElementName=root}" />
</StackPanel>
</UserControl>
対応ビハインドコードは次のようになります。
public static readonly DependencyProperty Text1Property = DependencyProperty.Register("Text1", typeof(String), typeof(CmpText));
public static readonly DependencyProperty Text2Property = DependencyProperty.Register("Text2", typeof(String), typeof(CmpText));
public string Text1
{
get { return (string)GetValue(Text1Property); }
set { SetValue(Text1Property, value); }
}
public string Text2
{
get { return (string)GetValue(Text2Property); }
set { SetValue(Text2Property, value); }
}
そして、これは私がMainWindow.xmlでこのユーザーコントロールを使用する方法です。
Text1とText2の両方が不一致の場合、2番目のTextBlockの背景色が赤に変更されます。
私はコードビハインドでヘルパープロパティを使用しようとしました:
public bool IsEqual { get { return Text1 == Text2; } }
そして
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEqual, ElementName=root}" Value="True">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
に2つ目のTextBlockのスタイルを設定するしかし、ISEQUALは常に(「真」であることが判明しましたText1 & Text2のプロパティが一致しない場合でも、TextBlockの背景は常に赤です)。私のヘルパープロパティ 'IsEqual'は、Text1 & Text2のデフォルト値をNULLと比較していると思います(私はGUIをデバッグできないので、それを確認する方法はありません)。したがって、IsEqualの評価は、テキストプロパティの値が割り当てられる前に発生するようです。の後に、評価が割り当てられるように、を入力します。
私は進行方法がわかりません。手伝ってくれますか?
+1私の優先オプションは#2になりますが – Rachel
はい、最も簡単な解決策です。さらに、#1は読み取り専用の依存関係プロパティでなければなりません。 – Clemens
まずは、ありがとうございます。私は解決策#2について質問があります。私はそれがINotifyPropertyChangedを実装する必要があるUserControl自体だと仮定していると仮定します。しかし、私が見る限り、 'Text1'と 'Text2'のPropertyChangedCallbacksは静的なものです...静的PropertyChangedCallback(DependencyPropertyの登録時にPropertyMetadataに渡すもの)は、非静的INotifyPropertyChanged.PropertyChangedイベント? – user1202727