値コンバーター(文字列入力をカラー出力に変換する)を使用する必要があります。最も簡単な解決策は、EmployeeViewModel に少なくとも 1 つのプロパティを追加することです。ある種のDefaultまたはOriginalValueプロパティを作成し、それと比較する必要があります。そうでなければ、「元の値」が何であったかをどのように知ることができますか? 比較する元の値を保持している何かがない限り、値が変更されたかどうかはわかりません。
したがって、テキスト プロパティにバインドし、入力文字列をビュー モデルの元の値と比較します。変更されている場合は、強調表示された背景色を返します。一致する場合は、通常の背景色を返します。FirstNameとLastNameを 1 つのテキスト ボックスから比較する場合は、マルチバインディングを使用する必要があります。
これがどのように機能するかを示す例を作成しました。
<Window x:Class="TestWpfApplication.Window11"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestWpfApplication"
Title="Window11" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
<local:ChangedDefaultColorConverter x:Key="changedDefaultColorConverter"/>
</Window.Resources>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock>Default String:</TextBlock>
<TextBlock Text="{Binding Path=DefaultString}" Margin="5,0"/>
</StackPanel>
<Border BorderThickness="3" CornerRadius="3"
BorderBrush="{Binding ElementName=textBox, Path=Text, Converter={StaticResource changedDefaultColorConverter}}">
<TextBox Name="textBox" Text="{Binding Path=DefaultString, Mode=OneTime}"/>
</Border>
</StackPanel>
Window のコード ビハインドは次のとおりです。
/// <summary>
/// Interaction logic for Window11.xaml
/// </summary>
public partial class Window11 : Window
{
public static string DefaultString
{
get { return "John Doe"; }
}
public Window11()
{
InitializeComponent();
}
}
最後に、使用するコンバーターは次のとおりです。
public class ChangedDefaultColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string text = (string)value;
return (text == Window11.DefaultString) ?
Brushes.Transparent :
Brushes.Yellow;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
また、TextBox の周りに境界線をラップしましたが (見た目が少し良くなったと思うため)、Background バインディングはまったく同じ方法で行うことができます。
<TextBox Name="textBox" Text="{Binding Path=DefaultString, Mode=OneTime}"
Background="{Binding ElementName=textBox, Path=Text, Converter={StaticResource changedDefaultColorConverter}}"/>