我在MVVM中使用Attached Property并遇到了一个有趣的问题。
我正在将一个名为WorkType的附加属性创建为一个按钮,如下所示:
public static DependencyProperty WorkTypeProperty = DependencyProperty.RegisterAttached("WorkType",
typeof(WorkTypeEnum),
typeof(MyControl),
new PropertyMetadata(WorkTypeChanged));
public static void SetWorkType(DependencyObject target, WorkTypeEnum value)
{
target.SetValue(WorkTypeProperty, value);
}
public static WorkTypeEnum GetWorkType(DependencyObject target)
{
return (WorkTypeEnum)target.GetValue(WorkTypeProperty);
}
public static void WorkTypeClick(object sender, MouseButtonEventArgs e)
{
var control = (Control)sender;
WorkTypeEnume workType = (WorkTypeEnum)control.GetValue(WorkTypeProperty);
(Instance of MyControl).DoWork(workType); ??? <--How to know the instance of MyControl?
}
private static void WorkTypeChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
var control = target as Control;
if (control != null)
{
if ((e.NewValue != null) && (e.OldValue == null))
{
control.MouseDown += WorkTypeClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
control.MouseDown -= WorkTypeClick;
}
}
}
我想知道如何将WorkType绑定到按钮,以便它将执行MyControl.DoWork(WorkTypeEnum workType)的实例?
无论如何我可以将MyControl的实例分配给按钮吗?
非常感谢你!