我使用SharpVector's SvgViewBox顯示靜態資源相似圖片:如何在不違反MVVM的情況下綁定到不可綁定的屬性?
<svgc:SvgViewbox Source="/Resources/label.svg"/>
工作正常。但是,我希望通過綁定視圖模型來控制顯示的圖像。
我遇到的問題是SvgViewbox的Source
屬性不可綁定。
如何在不違反MVVM的情況下繞過此限制(例如,將控件傳遞到視圖模型並在那裏修改它)?
我使用SharpVector's SvgViewBox顯示靜態資源相似圖片:如何在不違反MVVM的情況下綁定到不可綁定的屬性?
<svgc:SvgViewbox Source="/Resources/label.svg"/>
工作正常。但是,我希望通過綁定視圖模型來控制顯示的圖像。
我遇到的問題是SvgViewbox的Source
屬性不可綁定。
如何在不違反MVVM的情況下繞過此限制(例如,將控件傳遞到視圖模型並在那裏修改它)?
你在找什麼叫做附屬屬性。 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)
{
svgControl.Source = new Uri((string)e.NewValue);
}
}
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
財產。
這對我來說有一點小小的調整。因爲'svgControl.Source'是'Uri',所以使用'svgControl.Source = new Uri((string)e.NewValue)來設置它;' – burnttoast11
@ burnttoast11:謝謝,我解決了它。最初,我只是基於沒有查看所討論控件的具體API的問題編寫代碼。 – Tseng
什麼是「正確」,什麼是「動態」?你需要[編輯]並準確解釋你想要做什麼。 – Will
@你是對的。我修改了我的問題,添加了關於MVVM設計模式綁定的信息。 – Lukasz
這是你的問題。有很多方法可以解決這個問題。如果您查看我的編輯,您可能會理解這個問題通常如何描述。在閱讀此查詢中的問題時,您可能會發現一些解決方案http://stackoverflow.com/search?q=can%27t+bind+to+a+property+%5Bwpf%5D。 – Will