要執行這種驗證,您可以讓您的視圖模型類實現IDataErrorInfo
接口。
class MyViewModel : IDataErrorInfo
{
public string NewName { get; set; } // Notify property change here
public string OldName { get; set; } // Notify property change here
public string Error { get; private set; }
public string this[string property]
{
get
{
switch (property)
{
case "OldName":
case "NewName":
return OldName != NewName ? "Names are different" : null;
}
return null;
}
}
}
然後,你需要啓用驗證您的綁定:
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
:
<TextBox Grid.Row="2" Grid.Column="1"Height="20" Name="OldTextBox" Text="{Binding OldName, ValidatesOnDataErrors=True}" />
<TextBox Grid.Row="3" Grid.Column="1" Height="20" Name="NewTextBox" Text="{Binding NewName, ValidatesOnDataErrors=True}" />
如果需要的話,你可以通過你的樣式文本框改變背景顏色