繁体   English   中英

在 WPF 中绑定 Source 时图像不显示

[英]Image is not showing up when binding the Source in WPF

对于类似的问题,有一些解释,但我仍然不明白我做错了什么。 我在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 编辑器中看到图像:

在此处输入图片说明

现在我将 Usercontrol 添加到我的 MainWindow:

<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是错误的。

尝试

LSImage = new BitmapImage(new Uri(settings.Path, UriKind.RelativeOrAbsolute));

请注意,在Image.Source Binding 上设置NotifyOnSourceUpdated=True似乎毫无意义,因为您不使用 Binding 的SourceUpdated事件。

这足够了:

<Image Source="{Binding LSImage}"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM