C# 在WPF中绑定源时未显示图像
对于类似的问题有一些解释,但我仍然不明白我做错了什么。我在C:/Image.png中有一个图像 现在,我以MVVM模式启动了一个WPF项目,其中我有一个用于映像的usercontrol:C# 在WPF中绑定源时未显示图像,c#,wpf,mvvm,C#,Wpf,Mvvm,对于类似的问题有一些解释,但我仍然不明白我做错了什么。我在C:/Image.png中有一个图像 现在,我以MVVM模式启动了一个WPF项目,其中我有一个用于映像的usercontrol: <Grid> <Grid.DataContext> <vm:LSImageVM/> </Grid.DataContext> <Image x:Name="Picture" Source="{Binding LSIma
<Grid>
<Grid.DataContext>
<vm:LSImageVM/>
</Grid.DataContext>
<Image x:Name="Picture" Source="{Binding LSImage, NotifyOnSourceUpdated=True}"/>
</Grid>
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();
}
}
}
然后,在本例中,设置C:/Image.png中描述的路径被转换为BitmapImage,我将其用作在上述xaml中绑定的ImageSource
此时,当我构建项目时,我可以在我的xaml编辑器中看到图像:
现在,我将Usercontrol添加到我的主窗口:
<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>
这就是我启动程序时看不到图像的地方
我遗漏了什么?C:/Image.png不是相对URI,因此UriKind.relative是错误的
试一试
注意,在Image.Source绑定上设置NotifyOnSourceUpdated=True似乎没有意义,因为您没有使用绑定的SourceUpdated事件
这就足够了:
<Image Source="{Binding LSImage}"/>
C:/Image.png不是相对URI,因此UriKind.relative是错误的
试一试
注意,在Image.Source绑定上设置NotifyOnSourceUpdated=True似乎没有意义,因为您没有使用绑定的SourceUpdated事件
这就足够了:
<Image Source="{Binding LSImage}"/>
成功了。谢谢没有集中精力,因为图像在编辑器中是可见的。谢谢没有注意到这一点,因为图像在编辑器中是可见的。您可以将LSImage作为字符串执行同样的操作,并将图像的路径分配给它,这样就可以完成工作。您可以将LSImage作为字符串执行同样的操作,并将图像的路径分配给它,这样就可以完成工作。
<Image Source="{Binding LSImage}"/>