【问题标题】:Error binding to UserControl property if type is ImageSource in WinRT如果类型是 WinRT 中的 ImageSource,则绑定到 UserControl 属性时出错
【发布时间】: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


    【解决方案1】:

    ObservableCollection 在 WinRT 中不能正常工作(至少现在还不能),请改用 ObservableVector。有一个sample 提供了 IObservableVector 实现。

    【讨论】:

    • 我知道,我做到了.. 为了简单起见,我将这个问题改为 ObservableCollection。也不行
    • 哦,那不是问题。浏览了您的代码,对我来说看起来不错。注册时尝试初始化您的 PropertyMetadata。我将尝试运行此代码。
    • 设置 PropertyMetaData 也无济于事。
    猜你喜欢
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 1970-01-01
    • 2014-05-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多