【问题标题】:How to bind to an unbindable property without violating MVVM?如何在不违反 MVVM 的情况下绑定到不可绑定的属性?
【发布时间】:2016-05-04 09:02:47
【问题描述】:

我正在使用SharpVector's SvgViewBox 来显示这样的静态资源图像:

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

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

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

如何在不违反 MVVM 的情况下绕过这个限制(例如,将控件传递到视图模型并在那里修改它)?

【问题讨论】:

    标签: c# wpf svg mvvm data-binding


    【解决方案1】:

    您要查找的内容称为附加属性。 MSDN 提供了一个主题,标题为“Custom Attached Properties

    在你的情况下,它可能看起来很简单

    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"

    然后只使用您附加的属性 (local:Source) 而不要使用 Source 属性。

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

    【讨论】:

    • 这对我有用,只需稍作调整。由于svgControl.SourceUri,因此使用svgControl.Source = new Uri((string)e.NewValue); 设置它
    • @burnttoast11:谢谢,我修好了。最初,我仅根据问题编写代码,而没有查看相关控件的具体 API。
    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 2012-11-30
    • 2011-08-31
    相关资源
    最近更新 更多