该死的花了一段时间想出来,但一如既往,......附加的行为救援。
你在本质上看什么是脏状态跟踪。有许多方法可以使用ViewModel来完成此操作,但由于您不想更改实体,所以最好的方法是使用行为。
首先从Xaml绑定中移除ValidatesOnDataErrors。为您正在使用的控件(如下面显示的TextBox
)和TextChanged
事件(或任何您想要的事件)创建一个行为,将绑定重置为确实对进行验证。真的很简单。
这样,您的实体不必更改,您的Xaml保持合理清洁,并获得您的行为。
这里的代码 -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace IDataErrorInfoSample
{
public static class DirtyStateBehaviours
{
public static string GetDirtyBindingProperty(DependencyObject obj)
{
return (string)obj.GetValue(DirtyBindingPropertyProperty);
}
public static void SetDirtyBindingProperty(DependencyObject obj, string value)
{
obj.SetValue(DirtyBindingPropertyProperty, value);
}
// Using a DependencyProperty as the backing store for DirtyBindingProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DirtyBindingPropertyProperty =
DependencyProperty.RegisterAttached("DirtyBindingProperty", typeof(string), typeof(DirtyStateBehaviours),
new PropertyMetadata(new PropertyChangedCallback(Callback)));
public static void Callback(DependencyObject obj,
DependencyPropertyChangedEventArgs args)
{
var textbox = obj as TextBox;
textbox.TextChanged += (o, s) =>
{
Binding b = new Binding(GetDirtyBindingProperty(textbox));
b.ValidatesOnDataErrors = true;
textbox.SetBinding(TextBox.TextProperty, b);
};
}
}
}
行为和XAML是非常简单的了。
<Window x:Class="IDataErrorInfoSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:IDataErrorInfoSample"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow"
Height="350"
Width="525">
<Window.DataContext>
<local:Person />
</Window.DataContext>
<StackPanel Margin="20">
<TextBox Height="20"
Margin="0,0,0,10"
local:DirtyStateBehaviours.DirtyBindingProperty="Name"
Text="{Binding Path=Name}">
</TextBox>
<Button Content="Go" />
</StackPanel>
HTH,Stimul8d。
我在这个问题上付出了一笔赏金,希望得到一个非hacky解决方案(如果存在的话)。 – 2010-11-11 10:26:02
不能在调用InitializeComponent()之前创建Person吗? – markmnl 2011-03-08 02:44:06
增加了赏金,以获得一个好的非hacky解决方案.. – 2012-01-31 16:20:43