Silverlight中的动态图像源绑定
我想根据ChildWindow
DataContext
设置图像的源。 这是XAML文件:
... ...
如果我覆盖ChildWindow
的Show
方法并设置图像的源,它工作正常:
public new void Show() { DialogIcon.Source = new BitmapImage(new Uri(@"/Images/DialogWindow/Confirm.png", UriKind.Relative)); base.Show(); }
但它看起来很丑陋而且不是“silverlight方式”,所以我决定改变:
你看我注册了一个DialogIconConverter
来绑定DataContext
的源代码。
public class DialogIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { //currently it's an hard-coded path return new BitmapImage(new Uri(@"/Images/DialogWindow/Confirm.png", UriKind.Relative)); } ... }
但它现在不能正常工作,我在这个控件中有几个其他转换器工作正常。 只有这一个不起作用。 你能帮忙找出问题所在吗?
编辑: DialogIconType
是一个枚举,它也是DialogContext
的属性。 DialogContext
一个实例将被分配给DialogWindow
DataContext
属性。
public enum DialogIconType { Confirm, Alert, Error } public class DialogContext { public string Title { get; set; } public string Content { get; set; } public DialogButtons Buttons { get; set; } public DialogIconType IconType { get; set; } } internal DialogWindow(DialogContext context) { InitializeComponent(); this.DataContext = context; }
可能很傻,但你确定你的转换器在你的xaml文件中被正确引用了吗?
否则,我建议尝试将此语法作为URI的路径(将图像设置为资源):
return new BitmapImage(new Uri("pack://application:,,,/Images/DialogWindow/Confirm.png", UriKind.Relative));
编辑:
好吧,我想我已经明白了:看看你的输出窗口,你可能会看到一些错误40绑定… blablabla …
我的猜测是转换器是正确的,但绑定的来源不是,所以基本上甚至没有使用转换器。
原因是您的DialogIconType不是依赖属性,因此无法绑定。
换句话说,这个:
public DialogIconType IconType { get; set; }
应该成为这样的:
public static DependencyProperty IconTypeProperty = DependencyProperty.Register("IconType", typeof(DialogIconType), typeof(DialogContext)); public DialogIconType IconType { get { return (DialogIconType)(GetValue(IconTypeProperty)); } set { SetValue(IconTypeProperty , value); } }
另外,在你的Xaml中,你应该绑定到“IconType”,而不是“DialogIconType”(这是一个类型而不是属性)
(这甚至可能是唯一的问题,因为我不确定在这里是否真的需要dependencyProperty,现在我想起来了)
假设DialogIconType
是图像的路径(例如“Images / DialogWindow / Confirm.png”),它应该没有valueconverter,如下所示:
编辑:
从valueconverter的Convert
方法返回图像的路径也是可能的 – 即:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return "Images/DialogWindow/Confirm.png"; }
编辑2:
以下也适用于UriKind.Relative
:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return new BitmapImage(new Uri("Images/DialogWindow/Confirm.png", UriKind.Relative)); }