如何在不违反MVVM的情况下绑定到不可绑定的属性? [英] How to bind to an unbindable property without violating MVVM?

查看:105
本文介绍了如何在不违反MVVM的情况下绑定到不可绑定的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SharpVector的SvgViewBox 来显示静态资源图像,如下所示:

I am using SharpVector's SvgViewBox to show static resource images like this:

<svgc:SvgViewbox Source="/Resources/label.svg"/>

效果很好.但是,我希望通过绑定到视图模型来控制显示什么图像.

which works fine. However, I wish to control what image is shown through a binding to a view model.

我遇到的问题是SvgViewbox的Source属性不可绑定.

The problem I'm experiencing is that the Source property of SvgViewbox is not bindable.

如何克服此限制而又不违反MVVM(例如,将控件传递到视图模型中并在其中进行修改)?

How can I get around this limitation without violating MVVM (e.g., passing the control into the view model and modifying it there)?

推荐答案

您要查找的内容称为附加属性. MSDN为此主题提供了标题为"自定义附加属性"

What you are looking for is called attached properties. MSDN offers a topic on it with the title "Custom Attached Properties"

在您看来,它看起来像这样简单

In your case it may look as simple as this

namespace MyProject.Extensions 
{
    public class SvgViewboxAttachedProperties : DependencyObject
    {
        public static string GetSource(DependencyObject obj)
        {
            return (string) obj.GetValue(SourceProperty);
        }

        public static void SetSource(DependencyObject obj, string value)
        {
            obj.SetValue(SourceProperty, value);
        }

        private static void OnSourceChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var svgControl = obj as SvgViewbox;
            if (svgControl != null)
            {
                var path = (string)e.NewValue;
                svgControl.Source = string.IsNullOrWhiteSpace(path) ? default(Uri) : new Uri(path);
            }                
        }

        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.RegisterAttached("Source",
                typeof (string), typeof (SvgViewboxAttachedProperties),
                                    // default value: null
                new PropertyMetadata(null, OnSourceChanged));
    }
}

要使用它的XAML

<SvgViewbox Margin="0 200" 
    local:SvgViewboxAttachedProperties.Source="{Binding Path=ImagePath}" />

请注意,local是名称空间前缀,它应指向该类所在的程序集/名称空间,即xmlns:local="clr-namespace:MyProject.Extensions;assembly=MyProject".

Note that local is the namespace prefix and it should point to your assembly/namespace where that class is located at, i.e. xmlns:local="clr-namespace:MyProject.Extensions;assembly=MyProject".

然后仅使用您的附加属性(local:Source),而不使用Source属性.

Then only use your attached property (local:Source) and never the Source property.

新附加的属性local:Source的类型为System.Uri.要更新图像,请先分配null,然后再分配文件名/文件路径.

The new attached property local:Source is of type System.Uri. To update the image first assign null then the filename/filepath again.

这篇关于如何在不违反MVVM的情况下绑定到不可绑定的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆