[英]Data binding to an attached property
I have tried to use an Attached Property
to one of my controls in .NET 3.5. 我试图对.NET 3.5中的控件之一使用
Attached Property
。 The idea is that the control needs to be focused after a specific operation. 这个想法是控件需要在特定操作之后集中。 I wanted to bind this property to a value on the ViewModel, so that the property could be changed as needed (ie when I changed the value on the ViewModel, it would update the value in the Attached Property).
我想将此属性绑定到ViewModel的值,以便可以根据需要更改该属性(即,当我更改ViewModel的值时,它将更新Attached Property中的值)。
Attached Property 附属财产
class FocusProperty : DependencyObject
{
public static DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached ("IsFocused",
typeof (bool),
typeof (FocusProperty),
new UIPropertyMetadata (false, OnIsFocusedChanged));
public static bool GetIsFocused (DependencyObject DObject)
{
return (bool)DObject.GetValue (IsFocusedProperty);
}
public static void SetIsFocused (DependencyObject DObject, bool Value)
{
DObject.SetValue (IsFocusedProperty, Value);
}
public static void OnIsFocusedChanged (DependencyObject DObject, DependencyPropertyChangedEventArgs Args)
{
UIElement Control = DObject as UIElement;
bool NewValue = (bool)Args.NewValue;
bool OldValue = (bool)Args.OldValue;
// REMOVE TODO
System.Windows.MessageBox.Show ("OI");
if (NewValue && !OldValue && !Control.IsFocused)
{
Control.Focus ();
}
}
}
In the XAML, this is how it is used: 在XAML中,其用法如下:
a:FocusProperty.IsFocused="{Binding Path=IsListFocused}
Where IsListFocused
is a bool property on the ViewModel: 其中
IsListFocused
是ViewModel的bool属性:
public bool IsListFocused
{
get { return isListFocused_; }
set
{
isListFocused_ = value;
OnPropertyChanged ("IsFocused");
}
}
It doesn't work though - when the IsListFocused is changed, the MessageBox doesn't show up as expected. 但是它不起作用-更改IsListFocused后,MessageBox不会按预期显示。
I have been looking for help on the topic, but it seems like Attached Properties are not something used a lot, and as such there isn't much in the way of support. 我一直在寻求有关该主题的帮助,但似乎附加属性用处不大,因此,支持的方式也很少。
My question is: Why is the above snippet not working as expected? 我的问题是: 为什么以上代码片段无法按预期运行?
In the IsListFocused
property setter in your view model, replace 在视图模型的
IsListFocused
属性设置器中,替换
OnPropertyChanged("IsFocused");
by 通过
OnPropertyChanged("IsListFocused");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.