【问题标题】:Binding Image element to a property in uwp将图像元素绑定到 uwp 中的属性
【发布时间】:2016-03-23 00:29:46
【问题描述】:

我在 xaml 中有一个图像元素,我想将它与我的视图模型中的一个属性绑定。我将 xaml Image 元素绑定到名为 MainImage 的属性,如下所示。

private Image mainImage_ = new Image();
    public Image MainImage
    {
        get
        {
            return mainImage_;
        }
        set
        {
            if (mainImage_ != value)
            {
                mainImage_ = value;
                OnPropertyChanged("MainImage");
            }                                        
        }
    }

我想通过从计算机浏览它来将图像设置为 xaml 中的图像元素,我已经这样做了。

FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.FileTypeFilter.Clear();
        openPicker.FileTypeFilter.Add(".bmp");
        openPicker.FileTypeFilter.Add(".png");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".jpg");
        StorageFile file = await openPicker.PickSingleFileAsync();
        if (file != null)
        {
            IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read);
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.SetSource(fileStream);
            MainImage = bitmapImage;                    
            new MainPage().DataContext = file;                             
        }

MainImage = bitmapImage 显示无法直接设置的错误。 我该如何解决? 属性的返回类型应该是字符串(路径)还是图像? 如果有其他更好的方法,请告诉我。

【问题讨论】:

    标签: c# xaml windows-10 uwp


    【解决方案1】:

    你的视图模型属性应该是ImageSource,而不是Image

    private ImageSource mainImage;
    public ImageSource MainImage
    {
        get { return mainImage; }
        set
        {
            if (mainImage != value)
            {
                mainImage = value;
                OnPropertyChanged("MainImage");
            }                                        
        }
    }
    

    现在您可以将 XAML 中 Image 控件的 Source 属性绑定到您的视图模型,如下所示:

    <Image Source="{Binding MainImage}"/>
    

    但是,这需要将您的 Page 的 DataContext 设置为您的视图模型的实例,例如喜欢

    DataContext = new ViewModel();
    

    您不应该稍后将其设置为其他值,因为您似乎正在这样做

    new MainPage().DataContext = file;
    

    除此之外,还不清楚为什么要在该行中创建一个新的 MainPage 实例。

    【讨论】:

    • 非常感谢,它成功了。但是我直接在 xaml 中设置了数据上下文。
    【解决方案2】:

    您需要将图像的源属性设置为您的位图。试试:

                bitmapImage.UriSource = new Uri(img.BaseUri,file.Name);
                MainImage.Source = bitmapImage;
    

    编辑:抱歉,我没有看到 UWP,试试这个。

    【讨论】:

    • 它抛出 NullReferenceException。
    • 你确定 MainImage 正在初始化吗?
    • 上面给出的代码,就是我为此目的而写的。
    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2018-05-25
    • 2018-09-03
    • 1970-01-01
    • 2016-10-11
    • 2011-02-23
    相关资源
    最近更新 更多