简体   繁体   中英

Error binding to UserControl property if type is ImageSource in WinRT

Using the Windows 8 Developer Preview.

I have an object with one of the properties like this:

    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));
    }

This is used in an ObservableCollection like this:

        var test = new ObservableCollection<object>();

        ButtonItem item = new ButtonItem();
        item.SetImage(this.basUri, "Data/Images/test.png");

Where the test.png is included as content.

This collection is used to set the ItemsSource of a Grid, like so:

ItemGridView.ItemsSource = test;

And this Grid has an 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>

This MyButton is a user control of which the image property is a dependency property like so:

    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);
        }
    }

Now when I run this I get an exception:

An exception of type 'System.InvalidCastException' occurred in Test.exe but was not handled in user code

Additional information: Unable to cast COM object of type 'Windows.UI.Xaml.Data.Binding' to class type 'Windows.UI.Xaml.Media.ImageSource'

Now... when I convert the property on the usercontrol to a string type (and binding to a string), everything works as expected, so I must be doing something else wrong.. what?

ObservableCollection doesn't work properly (at least not yet) in WinRT, use ObservableVector instead. There is a sample that provides the IObservableVector implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM