C# 在WPF MVVM中绑定映像
将图像绑定到viewmodel时遇到问题。我终于摆脱了XamlParseException,但是图像没有出现。我甚至在ViewModel中对图像进行了硬编码。有人能看出我做错了什么吗 视图:C# 在WPF MVVM中绑定映像,c#,wpf,mvvm,C#,Wpf,Mvvm,将图像绑定到viewmodel时遇到问题。我终于摆脱了XamlParseException,但是图像没有出现。我甚至在ViewModel中对图像进行了硬编码。有人能看出我做错了什么吗 视图: 在WPF中显示图像要容易得多。试试这个: <Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" Margin="0,0,0,0" Name="image1" Stretch="Fill" Vertica
在WPF中显示
图像
要容易得多。试试这个:
<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" />
尽管您确实应该将图像添加到项目根目录中名为images
的文件夹中,并在Visual Studio的“属性”窗口中将其生成操作设置为“资源”。。。然后,您可以使用以下格式访问它们:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
更新>>> 作为最后的提示。。。如果您遇到控件无法正常工作的问题,只需在搜索引擎中键入“WPF”、该控件的名称,然后键入单词“class”。在本例中,您应该键入“WPF图像类”。最重要的结果总是MSDN,如果您单击该链接,您将了解有关该控件的所有信息,并且大多数页面都有代码示例
更新2>>> 如果您按照MSDN链接中的示例进行操作,但该链接不起作用,那么您的问题不是
图像
控件。使用我建议的string
属性,尝试以下操作:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
有关包URI的更多信息,请参阅Microsoft文档页面
@谢里登thx。。如果我试着用两边的“DisplayedImagePath”来演示您的示例,它会像您所展示的那样使用绝对路径 至于相对路径,我总是这样连接相对路径,我首先在项目中包括子目录(!)和图像文件。。然后我使用~字符表示bin路径
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
这是经过测试的,请参见下面VS2015中的“我的解决方案资源管理器”
)
注意:如果需要单击事件,请使用
如果您有一个已经生成并返回图像类型的进程,您可以更改绑定,而无需修改任何其他图像创建代码 请参阅绑定语句中图像的“.Source” XAML
谢谢你的回复。我尝试了这段代码,在DisplayeImage中设置了一个断点,它肯定正在被访问,但没有图像。对不起,这意味着表单上没有图像。如果我将路径直接放在XAML中,图像显示。是的,对不起,我没有正确地看到您的属性。。。比那更容易。看我的编辑。好吧,这让我一事无成。有人用绑定的wpf映像测试过代码吗?我非常抱歉没有早点得到这个。谢谢你,谢里登。我在选项卡控件上有两个选项卡,每个选项卡上使用相同的UserControl,但区别在于绑定。你上次的更新让我意识到我看错了标签,因为绑定没有设置。谢谢你的帮助。你太棒了。
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>
private Image _imageOpenClose;
public Image ImageOpenClose
{
get
{
return _imageOpenClose;
}
set
{
_imageOpenClose = value;
OnPropertyChanged();
}
}