在下面的代碼中,當在組合框中輸入無效值(例如「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