【发布时间】:2012-03-14 14:43:14
【问题描述】:
一个窗口有两个背景图像,具体取决于用户在窗口中所在的导航页面。这些图像位于我的项目文件夹中的位置:
/Resources/Images/MyImage1.jpg
如果我使用 IDE 选择固定的背景图像,则 xaml 文件将更新为:
<NavigationWindow.Background>
<ImageBrush ImageSource="/Blah.MyApp;component/Resources/Images/MyImage1.jpg" />
</NavigationWindow.Background>
这样可以正确显示图像。
但是,由于我希望图像切换,我为 Window 创建了一个 ViewModel(它实现了 INotifyPropertyChanged),它公开了一个 Uri 属性,如下所示:
private readonly string _image1 = "pack://application:,,,/Resources/Images/MyImage1.jpg";
private readonly string _image2 = "pack://application:,,,/Resources/Images/MyImage2.jpg";
public MainNavWindowViewModel()
{
SetImage1();
}
private Uri _backgroundImg;
public Uri BackgroundImg
{
get
{
return _backgroundImg;
}
private set
{
_backgroundImg = value;
OnPropertyChanged("BackgroundImg");
}
}
public void SetImage1()
{
BackgroundImg = new Uri(_image1);
}
public void SetImage2()
{
BackgroundImg = new Uri(_image2);
}
在主窗口的 xaml 文件中,我已将 NavigationWindow.Background 替换为:
<NavigationWindow.Background>
<ImageBrush ImageSource="{Binding Path=BackgroundImg, Mode=OneWay}" />
</NavigationWindow.Background>
并将 Windows 的 DataContext 设置为 ViewModel。
但是,此功能只是在我的窗口上显示黑色背景(当我注释掉将 ViewModel 数据绑定到窗口的行时,这是相同的行为)。
我将 ViewModel 设置为 Window 构造函数的第一行中的 Datacontext。如果我在上面设置断点,它会执行这些行并且看起来没问题。
任何想法发生了什么或我如何找出问题所在?
TIA
【问题讨论】:
标签: c# wpf data-binding viewmodel