当RaisePropertyChanged时,MVVM DependencyProperty不会更新

时间:2012-03-27 16:15:35

标签: wpf

我有usercontrol,并且在其中定义了DependencyProperty。

        #region ImageUri
    public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register(
       "ImageUri",
       typeof(string),
       typeof(ScrollableCanvas),
       new PropertyMetadata(new PropertyChangedCallback(ImageUriPropertyChangedCallback)));

    private static void ImageUriPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        ScrollableCanvas main = sender as ScrollableCanvas;
        if (main != null)
        {
            main.ImageUri = (string)e.NewValue;
        }
    }

    public string ImageUri
    {
        get
        {
            return (string)GetValue(ImageUriProperty);
        }
        set
        {
            SetValue(ImageUriProperty, value);
            UpdateImage();
        }
    }
    #endregion

在Xaml中,我像这样绑定一个值

<my:ScrollableCanvas  Name="scrollableCanvas1" ImageUri="{Binding Path=LayerImage}" />

当我在viewmodel中更新LayerImage时,ImageUri属性不会更新。

可以对此有所帮助吗?感谢。

BTW:当我在viewmodel的构造函数中设置LayerImage时,该值会更新。

1 个答案:

答案 0 :(得分:0)

你不应该在你的二传手中加入UpdateImage来电,而应该在属性更改回调中。

public static readonly DependencyProperty ImageUriProperty = DependencyProperty.Register(
   "ImageUri",
   typeof(string),
   typeof(ScrollableCanvas),
   new PropertyMetadata(new PropertyChangedCallback(ImageUriPropertyChangedCallback)));

private static void ImageUriPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    ScrollableCanvas main = sender as ScrollableCanvas;
    if (main != null)
    {
        // Since ImageUri has already been called at this point, you can just update your image here...
        main.UpdateImage();
    }
}

public string ImageUri
{
    get
    {
        return (string)GetValue(ImageUriProperty);
    }
    set
    {
        SetValue(ImageUriProperty, value);
    }
}