自定义DependencyProperty不能与viewmodel绑定?

时间:2013-01-28 16:05:26

标签: wpf viewmodel dependency-properties

考虑这个附加属性:

public static readonly DependencyProperty TestImageProperty =
    DependencyProperty.RegisterAttached("TestImage",
    typeof(BitmapSource), typeof(TestView), new FrameworkPropertyMetadata(null,
    FrameworkPropertyMetadataOptions.AffectsRender));

public static void SetTestImage(UIElement element, BitmapSource value)
{
    element.SetValue(TestImageProperty, value);
}

public static BitmapSource GetTestImage(UIElement element)
{
    return (BitmapSource)element.GetValue(TestImageProperty);
}

public BitmapSource TestImage
{
    get
    {
        return GetTestImage(this);
    }
    set
    {
        SetTestImage(this, value);
    }
}

XAML

<common:UserControlBase x:Class="MyViews.TestView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:views="clr-namespace:MyViews"
    xmlns:common="clr-namespace:MyCommon.Common;assembly=MyCommon.Common"
    xmlns:mefed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
    mefed:ViewModelLocator.SharedViewModel="MyViewModel"
    views:TestView.TestImage="{Binding TestImage}"

因此,我将视图的TestImage属性绑定到viewmodel的TestImage属性!然后,从代码隐藏更新属性:

this.TestImage = image;

这不会触发我的viewmodel中的setter。

造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:0)

Binding置于TwoWay模式将解决问题。