I have a UserControl that exists of only two TextBlocks:
<UserControl [...] x:Name="root">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Text1, ElementName=root}" />
<TextBlock Text="{Binding Text2, ElementName=root}" />
</StackPanel>
</UserControl>
The corresponding code-behind looks like this:
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); }
}
And this is how I use this UserControl in MainWindow.xml:
<local:CmpText Text1="{Binding Password1}" Text2="{Binding Password2}" />
What I basically want is the second TextBlock’s background to change its color to red if both Text1 and Text2 are unequal.
I tried to use a helper property in the code-behind:
public bool IsEqual { get { return Text1 == Text2; } }
And set the second TextBlock’s Style to
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsEqual, ElementName=root}" Value="True">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
However, IsEqual always turns out to be ‘true’ (and the TextBlock’s background is always red) even if the Text1 & Text2 properties don’t match. I think my helper property ‘IsEqual’ compares the default values of Text1 & Text2, which happen to be NULL (I don’t have any way to confirm that, since I cannot debug the GUI). So the evaluation of IsEqual seems to happen before my text properties get assigned any values. I want the evaluation to happen after the text properties get assigned.
I don’t know how to proceed. Can you help?
Currently there is no way that WPF could find out that
IsEqualhas changed, so the binding won’t be re-evaluated.You could do three things:
Make
IsEqualanother dependency property and add PropertyChangedCallbacks to theText1andText2which, whenever they change, updateIsEqual.Or, implement INotifyPropertyChanged and raise the PropertyChanged event for
IsEqualin theText1andText2PropertyChangedCallbacks.Or, use a MultiBinding in conjunction with a IMultiValueConverter to bind the Background property directly to
Text1andText2. The converter would get two strings as input and return a Brush.