如何在不违反MVVM的情况下绑定到不可绑定的属性?

编程入门 行业动态 更新时间:2024-10-28 07:29:46
本文介绍了如何在不违反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的情况下绑定到不可绑定的属性?

本文发布于:2023-10-09 02:15:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   属性   情况下   如何在   MVVM

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!