有没有办法改变绑定的默认行为,所以我不需要设置'UpdateSourceTrigger = PropertyChanged'在每个,在我的情况下,文本框?有没有办法在wpf中全局更改绑定的默认行为?
可以通过ControlTemplate或Style来完成吗?
有没有办法改变绑定的默认行为,所以我不需要设置'UpdateSourceTrigger = PropertyChanged'在每个,在我的情况下,文本框?有没有办法在wpf中全局更改绑定的默认行为?
可以通过ControlTemplate或Style来完成吗?
也许是更适合覆盖缺省为您绑定,您可以用这一个用于此目的:
http://www.hardcodet.net/2008/04/wpf-custom-binding-class
然后定义一些CustomBinding类(在构造函数中设置适当的默认值)和MarkupExtension'CustomBindingExtension'。 然后通过这样的替换您的XAML绑定:
文本=“{CustomBinding路径= XY ...}”
我已经成功地尝试与绑定类似,设置一定的ValidatesOnDataError和NotifyOnValidationError的缺省值也应该适用于你的情况。 问题是,如果您愿意替换所有绑定,但可以自动执行此任务。
号此行为是由FrameworkPropertyMetadata
类,登记DependencyProperty
时被传递的DefaultUpdateSourceTrigger
处理。可以在继承的类TextBox
和每个绑定中覆盖此值,但不能在应用程序中的每个TextBox
中覆盖此值。
像彼得建议我用继承的类像这样解决了这个问题:
public class ActiveTextBox:TextBox
{
public ActiveTextBox()
{
Loaded += ActiveTextBox_Loaded;
}
void ActiveTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
Binding myBinding = BindingOperations.GetBinding(this, TextProperty);
if (myBinding != null && myBinding.UpdateSourceTrigger != UpdateSourceTrigger.PropertyChanged)
{
Binding bind = (Binding) Allkort3.Common.Extensions.Extensions.CloneProperties(myBinding);
bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
BindingOperations.SetBinding(this, TextBox.TextProperty, bind);
}
}
}
这helpmethod:
public static object CloneProperties(object o)
{
var type = o.GetType();
var clone = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
if (property.GetSetMethod() != null && property.GetValue(o, null) != null)
property.SetValue(clone, property.GetValue(o, null), null);
}
return clone;
}
任何建议如何解决它更好?
'DependencyProperty.OverrideMetadata()'是一个更好的策略。你可以像'TextBox.TextProperty.OverrideMetadata(typeof(ActiveTextBox),<< properties >>)一样使用'TextProperty'。 – 2010-11-03 09:39:22
类似的东西?: var defaultMetadata = TextProperty.GetMetadata(typeof(TextBox)); TextProperty.OverrideMetadata(typeof运算(ActiveTextBox),新FrameworkPropertyMetadata( 的String.Empty,FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, defaultMetadata.PropertyChangedCallback, defaultMetadata.CoerceValueCallback, 真实, System.Windows.Data.UpdateSourceTrigger.PropertyChanged) ); – Cinaird 2010-11-04 08:27:37
我会尝试解决方案蚂蚁感谢您的信息。 – Cinaird 2010-11-03 09:00:37