我在将图像绑定(bind)到我的 View 模型时遇到了一些问题。我终于摆脱了 XamlParseException,但图像没有出现。我什至在 ViewModel 中对图像进行了硬编码。有人可以看到我做错了什么吗?
查看:
<Image HorizontalAlignment="Left" Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" Grid.Row="8" Width="200" Grid.ColumnSpan="2" >
<Image.Source>
<BitmapImage DecodePixelWidth="200" UriSource="{Binding Path=DisplayedImage, Mode=TwoWay}" />
</Image.Source>
View 模型:
string _DisplayedImagePath = @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";//string.Empty;
int _DisplayedImageIndex;
BitmapImage _DisplayedImage = null;
public BitmapImage DisplayedImage
{
get
{
_DisplayedImage = new BitmapImage();
if (!string.IsNullOrEmpty(_DisplayedImagePath))
{
_Rail1DisplayedImage.BeginInit();
_Rail1DisplayedImage.CacheOption = BitmapCacheOption.OnLoad;
_Rail1DisplayedImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
_Rail1DisplayedImage.UriSource = new Uri(_DisplayedImagePath);
_Rail1DisplayedImage.DecodePixelWidth = 200;
_Rail1DisplayedImage.EndInit();
}
return _Rail1DisplayedImage;
}
set
{
_Rail1DisplayedImage = value;
OnPropertyChanged("DisplayedImage");
}
}
最佳答案
在 WPF 中显示 Image
比这容易得多。试试这个:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
并且该属性可以只是一个字符串
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
尽管您确实应该将图像添加到项目根目录中名为 Images
的文件夹中,并将它们的Build Action 设置为 Resource Visual Studio 中的 Properties 窗口...然后您可以使用以下格式访问它们:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
更新>>>
作为最后的提示...如果您遇到控件无法按预期工作的问题,只需在搜索引擎中输入“WPF”、该控件的名称,然后再输入“类”。在这种情况下,您将键入“WPF Image Class”。最上面的结果将始终是 MSDN,如果您单击该链接,您将找到有关该控件的所有信息,并且大多数页面也有代码示例。
更新 2 >>>
如果您按照 MSDN 链接中的示例进行操作但它不起作用,那么您的问题不是 Image
控件。使用我建议的 string
属性,试试这个:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
如果您在 TextBlock
中看不到文件路径,那么您可能还没有将 DataContext
设置为 View 模型的实例。如果您可以看到文本,那么问题出在您的文件路径上。
更新 3 >>>
在 .NET 4 中,上面的 Image.Source
值可以工作。但是,Microsoft 在 .NET 4.5 中进行了一些可怕的更改,这些更改破坏了许多不同的东西,因此在 .NET 4.5 中,您需要像这样使用完整的 pack
路径:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
关于c# - 在 WPF MVVM 中绑定(bind)图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788855/