以下ViewModel代码加载图像,然后将其设置为AppBackground
属性:
public class ShellViewModel : BindableBase
{
public ShellViewModel()
{
var Stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("Application.Resources.Images.Background.jpg");
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = Stream;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
AppBackground = bi;
}
public ImageSource AppBackground
{
get { return _AppBackground; }
set { SetProperty(ref _AppBackground, value); }
}
ImageSource _AppBackground;
}
只需添加此命令,图像就会正确显示:
<Grid>
<Grid.Background>
<ImageBrush ImageSource="{Binding AppBackground}" />
</Grid.Background>
...
</Grid>
现在,我希望将图像封装在类中,例如Settings
,然后通过接口ISettings
传递它,然后使用MEF导出它并将其导入到viewmodel中:< / p>
public class ShellViewModel : BindableBase
{
[Import]
public ISettings Settings
{
get { return _Settings; }
set { SetProperty(ref _Settings, value); }
}
ISettings _Settings;
}
图像加载在Settings
类中完成:
public class Settings : BindableBase, ISettings
{
public Settings()
{
var Stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("Application.Resources.Images.Background.jpg");
var bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = Stream;
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.EndInit();
AppBackground = bi;
}
public ImageSource AppBackground
{
get { return _AppBackground; }
set { SetProperty(ref _AppBackground, value); }
}
ImageSource _AppBackground;
}
ISettings
接口的定义是:
[InheritedExport(typeof(ISettings))]
public interface ISettings
{
ImageSource AppBackground { set; get; }
}
最后,通过更改xaml代码:
<Grid>
<Grid.Background>
<ImageBrush ImageSource="{Binding Settings.AppBackground}" />
</Grid.Background>
...
</Grid>
不显示图像。
System.Windows.Media.Imaging.BitmapImage
当我在同一视图中添加以下代码时:
<TextBlock Text="{Binding Settings.AppBackground}" />
{Binding Settings.AppBackground}
路径按原样运行。我希望它不是真的最后一次。