在ViewModel中访问DependencyPropertyValue

时间:2013-07-26 19:40:57

标签: c# wpf mvvm dependency-properties

假设我在具有DependencyProperty的Control的DataContext中有一个ViewModel:

AControl.cs:

class AControl : Control /* could be another class e.g. Viewbox, Label */
{
    public AControl()
    {
        DataContext = new AControlViewModel(/* this ?? */);
    }


    public int AProperty
    {
        get { return (int)GetValue(APropertyProperty); }
        set { SetValue(APropertyProperty, value); }
    }

    public static readonly DependencyProperty APropertyProperty =
        DependencyProperty.Register("AProperty", typeof(int), 
        typeof(AClass), new FrameworkPropertyMetadata(0));
}

AControlViewModel.cs:

class AControlViewModel : ViewModelBase
{
    void SomeMethod()
    {
        // Some actions accessing AProperty for the Control 
        // in whose DataContext 'this' is in
    }

    // EDIT: Property added
    private int vMProperty;
    public int VMProperty 
    {
        get { return vMProperty; }
        set
        {
             if (vMProperty == value)
                 return;

             vMProperty = value;
             OnPropertyChanged("VMProperty"); // In ViewModelBase
        } 
    } 
}

我知道可以从Control传递this-reference,但只能从codebehind传递。如何做到这一点(如果有一个比传递引用更简单的方法)和如何从Xaml做到这一点? 如果AProperty的价值发生变化,如何获得通知?

修改 在另一个控件的风格:

<Style TargetType="{x:Type namespace:AnotherControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type namespace:AnotherControl}"> 
                <Border>
                    <namespace:AControl AProperty="{TemplateBinding AnotherProperty}">
                        <!-- This Binding replaces the Binding 'AProperty="{Binding VMProperty}' inside AControl. 
                             I think I have to bind to VMProperty instead of AProperty... but how?-->
                    </namespace:AControl> 
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style> 

1 个答案:

答案 0 :(得分:2)

将属性(包括INotifyPropertyChanged实现)添加到ViewModel并将其绑定到视图的属性。

那就是它。

现在,您可以在视图中访问该属性的值。

不要尝试在ViewModel中获取对View的引用,这样就可以打破MVVM模式。