【问题标题】:Image is not showing up when binding the Source in WPF在 WPF 中绑定源时图像未显示
【发布时间】: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 作为字符串执行相同的操作,并将图像的路径分配给它即可完成工作。

标签: c# wpf mvvm


【解决方案1】:

C:/Image.png 不是相对 URI,因此UriKind.Relative 是错误的。

试试

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

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

这就足够了:

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

【讨论】:

  • 做到了。谢谢。没有关注那个,因为图像在编辑器中可见
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-25
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多