如何使用带有ViewFirst View Injection的Prism和MVVM将图像加载(绑定)到viewmodel中的属性?

时间:2013-03-18 18:21:26

标签: wpf image prism

使用Prism,MVVM和View First View注入:无法在模块中加载图像

我使用View First,View Injection模式在MVVM模式中使用WPF和Prism。

在我的解决方案中,我有一个SG.BannerModule项目,我只想在BannerView.xaml中绑定一个Image。 我使用下面实现IBannerViewModel的BannerViewModel,因为我使用容器来解析我的BannerViewModel。 这是IBannerViewModel接口:

public interface IBannerViewModel : IViewModel
{
    Uri BannerImageUri { get; set; }
}

我暴露了BannerImageUri因为我通过容器解析了BannerViewModel BannerMainModule使用接口。

BannerViewModel实现

public class BannerViewModel : ViewModelBase, IBannerViewModel
{

    #region Properties

    private IUnityContainer _container;
    private ILogger _logger;

    private Uri _bannerImageUri;
    public Uri BannerImageUri
    {
        get { return new Uri("pack://SG.Website:,,,SG.BannerModule;component/Assets/SGBanner2.png"); }
        set
        {
            if (value != _bannerImageUri)
            {
                _bannerImageUri = value;
                OnPropertyChanged("BannerImageUri");
            }

        }
    }

     #endregion

    #region Constructors

    public BannerViewModel(IBannerView bannerView, IUnityContainer container)
        : base(bannerView)
    {
        View = bannerView;
        View.ViewModel = this;

        _container = container;
        _logger = _container.Resolve<ILogger>();

        _logger.WriteToLogs("BannerViewModel Constructor");
    } 
    #endregion

 }

Image位于我的SG.BannerModule项目的Assets目录中。 我已将Image SGBanner2.png的构建属性设置为资源,并已在SG.BannerModule项目的“属性”窗格的“资源”选项卡中添加了该图像。 我已经按照以下方式在BannerView.xaml.cs文件中设置了BannerView.xaml的数据上下文,因为我正在使用View Injection。

public partial class BannerView : UserControl, IBannerView
{
    public BannerView()
    {
        InitializeComponent();
    }

    public IViewModel ViewModel
    {
        get 
        { 
            return (IBannerViewModel) DataContext; 
        }
        set { DataContext = value; }
    }

}

由于View First View Injection模式,我在后面的代码中设置了DataContext,并且没有在XAML中设置任何。

我的问题是

  1. 因为我绑定了这张图片,我是否需要使用ImageSource转换器?如果是这种情况,它会成为一个问题,因为图像是png而不是位图吗?
  2. 或者是Pack Uri的问题。因为我在我的SG.WebSite项目的某个区域中使用此模块,所以我不确定我的包Uri是否正确但我无法正确拍摄为什么我的图像没有显示在我的shell窗口中。 难倒?
  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

您知道,似乎您首先使用的是ViewModel。让ViewModel解析View,然后调用region.Add(viewModel.View)。

这是本地资源文件的packURI语法:

pack:// application:,,, / Subfolder / ResourceFile.xaml

对于参考资源文件:

包://应用:,,, / ReferencedAssembly;组件/子文件夹/ ResourceFile.xaml