【发布时间】:2012-02-14 08:12:53
【问题描述】:
使用 Windows 8 开发者预览版。
我有一个具有以下属性之一的对象:
private ImageSource _Image = null;
public ImageSource Image
{
get
{
return this._Image;
}
set
{
if (this._Image != value)
{
this._Image = value;
this.OnPropertyChanged("Image");
}
}
}
public void SetImage(Uri baseUri, String path)
{
Image = new BitmapImage(new Uri(baseUri, path));
}
这在 ObservableCollection 中使用如下:
var test = new ObservableCollection<object>();
ButtonItem item = new ButtonItem();
item.SetImage(this.basUri, "Data/Images/test.png");
test.png 作为内容包含在哪里。
这个集合用来设置一个Grid的ItemsSource,像这样:
ItemGridView.ItemsSource = test;
而且这个 Grid 有一个 DataTemplate:
<DataTemplate x:Key="testtemp">
<Grid HorizontalAlignment="Left" Background="White">
<StackPanel Orientation="Horizontal" Margin="10,10,0,0">
<my:MyButton Image="{Binding Image}"></my:MyButton>
</StackPanel>
</Grid>
</DataTemplate>
这个 MyButton 是一个用户控件,它的 image 属性是一个依赖属性,如下所示:
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("Image", "ImageSource", typeof(VSButton).FullName, null);
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set
{
SetValue(ImageSourceProperty, value);
}
}
现在当我运行它时,我得到一个异常:
Test.exe 中出现“System.InvalidCastException”类型的异常,但未在用户代码中处理
附加信息:无法将“Windows.UI.Xaml.Data.Binding”类型的 COM 对象转换为“Windows.UI.Xaml.Media.ImageSource”类类型
现在...当我将用户控件上的属性转换为字符串类型(并绑定到字符串)时,一切都按预期工作,所以我一定做错了什么......什么?
【问题讨论】:
标签: c# data-binding windows-runtime