【发布时间】:2020-01-22 09:24:14
【问题描述】:
对于类似的问题有一些解释,但我仍然不明白我做错了什么。我在C:/Image.png 中有一张图片。
现在我在 MVVM-Pattern 中启动了一个 WPF 项目,其中我有一个图像的用户控件:
<Grid>
<Grid.DataContext>
<vm:LSImageVM/>
</Grid.DataContext>
<Image x:Name="Picture" Source="{Binding LSImage, NotifyOnSourceUpdated=True}"/>
</Grid>
这是图像的 Viewmodel-Class:
public class LSImageVM : ViewModelBase
{
private ImageSource _image;
private LockscreenSettingsClass settings;
public LSImageVM()
{
var json = File.ReadAllText("C:/Program Files/LSL/settings.json");
settings = JsonConvert.DeserializeObject<LockscreenSettingsClass>(json);
Uri imageUri = new Uri(settings.Path, UriKind.Relative);
BitmapImage imageBitmap = new BitmapImage(imageUri);
LSImage = imageBitmap;
}
public ImageSource LSImage
{
get => _image;
set
{
_image = value;
OnPropertyChanged();
}
}
}
所以我从一个 Json 中获取我的设置,如下所示:
{
"Path": "C:/Image.png",
"Interval": 5000,
"LogPath": "C:/Lockscreen.log"
}
然后设置中描述的路径(在这种情况下为C:/Image.png)被转换为BitmapImage,我将其用作我在上面的xaml中绑定的ImageSource。
此时,当我构建项目时,我可以在我的 xaml-editor 中看到图像:
现在我将用户控件添加到我的主窗口:
<Window x:Class="LockscreenSettings_MVVM.View.Windows.Main_Window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:LockscreenSettings.View.UserControls"
xmlns:local="clr-namespace:LockscreenSettings_MVVM.View.Windows"
mc:Ignorable="d"
Title="Main_Window" Height="500" Width="400" ResizeMode="NoResize">
<Grid>
<uc:LSImageUC/>
</Grid>
</Window>
这就是我启动程序时看不到图像的地方。
我错过了什么?
【问题讨论】:
-
您可以将 LSImage 作为字符串执行相同的操作,并将图像的路径分配给它即可完成工作。