使用Caliburn.Micro将图像从视图模型加载到视图中

本文关键字:视图 模型 加载 Caliburn Micro 图像 使用 | 更新日期: 2023-09-27 18:33:05

我试图让用户在视图中加载图像。

我的主要观点:

<UserControl x:Class="TestApplication.Views.MainView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="0.3*" />
        </Grid.ColumnDefinitions>
        <Image
            Grid.Column="0"
            Stretch="Uniform"
            x:Name="Preview">
            <Image.Source>
                <BitmapImage UriSource="pack://application:,,,/Resources/placeholder.jpg" />
            </Image.Source>
        </Image>
        <ContentControl
            Grid.Column="1"
            x:Name="ImageManagement" />
    </Grid>
</UserControl>

我的主要视图模型:

namespace TestApplication.ViewModels
{
    using System;
    using System.ComponentModel.Composition;
    using System.Windows.Controls;
    using Caliburn.Micro;
    using PropertyChanged;
    using TestApplication.Events;
    [ImplementPropertyChanged]
    [Export(typeof(MainViewModel))]
    public class MainViewModel : PropertyChangedBase, IHandle<FileSelectedEvent>
    {
        private readonly IEventAggregator events;
        [ImportingConstructor]
        public MainViewModel(IEventAggregator events)
        {
            this.events = events;
            this.events.Subscribe(this);
            this.ImageManagement = new ImageManagementViewModel(events);
        }
        public ImageManagementViewModel ImageManagement { get; set; }
        public Image Preview { get; set; }
        public void Handle(FileSelectedEvent message)
        {
            // load the selected image
        }
    }
}

图像占位符不显示,窥探甚至看不到它。

此外,当通过实例化BitmapImage并将其设置为Handle方法中的Preview.Source来加载图像时......Preview属性为 null,如果我先初始化它,它也永远不会显示。

PropertyChanged 通过 Fody 处理。

使用Caliburn.Micro将图像从视图模型加载到视图中

感谢@Will和@mvermef,我找到了答案。

占位符 URL 并非无效,但它在没有pack://部分的情况下确实有效。不过,我喜欢它,因为这样就明确表示它是一个资源而不是一个文件。

真正的问题是,事实上,Caliburn.Micro实际上并没有绑定到控件,而是绑定到Source属性。切换到这个解决了这个问题:

    <Image
        Grid.Column="0"
        Stretch="Uniform"
        Source="{Binding PreviewUrl}" />

和视图模型:

    [ImportingConstructor]
    public MainViewModel(IEventAggregator events)
    {
        this.events = events;
        this.events.Subscribe(this);
        this.ImageManagement = new ImageManagementViewModel(events);
        this.PreviewUrl = "pack://application:,,,/Resources/placeholder.jpg";
    }
    public String PreviewUrl { get; set; }
    public void Handle(FileSelectedEvent message)
    {
        this.PreviewUrl = message.FilePath;
    }