MVVM附加属性目标和原始控件

时间:2012-02-03 02:01:08

标签: mvvm attached-properties

我在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的实例分配给按钮吗?

非常感谢你!

1 个答案:

答案 0 :(得分:0)

您正在使用附加属性,没有MyControl的实例。如果您想在按下按钮时传递参数,可能需要使用Commands来查看。