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

时间:2014-12-04 17:42:40

标签: c# wpf mvvm caliburn.micro

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

我的主要观点:

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

不显示图像占位符,而snoop甚至看不到它。

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

PropertyChanged通过Fody处理。

1 个答案:

答案 0 :(得分:0)

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

占位符网址无效,但在没有pack://部分的情况下确实有效。不过,我喜欢它,因为它显然是资源而不是文件。

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

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

和viewmodel:

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