在下面的代码中,当在组合框中输入无效值(例如“a”)时,会引发异常,并且WPF会将Validation.HasError设置为true。组合框触发器忠实地将背景设置为蓝色。不过,我希望Tag属性也设置为'true',并且由于它是基础数据环境中的B的数据绑定,所以您可能希望B也更新为'true'。然而,据我所知,当验证失败时,绑定引擎停止并且不运行任何转换器 - 下面的ConvertBack方法根本不被调用。为什么Tag属性不被更新?
但是,snoop实用程序显示标签保持其“默认”值(由datacontext中的属性B给出)。
任何洞悉为什么将不胜感激。
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="ComboBox">
<Style.Triggers>
<Trigger Property = "Validation.HasError" Value = "true">
<Setter Property="Tag" Value="true"/>
<Setter Property="Background" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel>
<ComboBox Height="23" IsEditable="True" Name="comboBox1" Width="120"
Tag="{Binding Path=B, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource MyConverter}}"
Text="{Binding Path=A, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContextClass dataContext = new DataContextClass();
this.DataContext = dataContext ;
}
}
public class DataContextClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private string b = "default";
public string B
{
get { return b; }
set
{
b = value;
PropertyChanged(this, new PropertyChangedEventArgs("B"));
}
}
private int a;
public int A
{
get { return a; }
set
{
a = value;
PropertyChanged(this, new PropertyChangedEventArgs("A"));
}
}
}
public class MyConverter : IValueConverter
{
#region Public Methods
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value as string;
}
#endregion
}
验证在哪里? – kaj 2012-03-03 10:51:36
@KAJ validatesonexceptions = true绑定Text属性 – sturdytree 2012-03-03 10:53:00
不,是什么让“a”成为无效值? – kaj 2012-03-03 10:54:57