我试图有一个带有图像和文本的按钮,并使用绑定(bind)到我的 ButtonCommandViewModel。我的 ButtonCommandViewModel 中需要什么样的属性才能使图像绑定(bind)到符合 MVVM 概念的属性?我应该只有一个图像、一个 URL 或某种图像标签可以通过转换器运行的字符串吗?
<Button Command="{Binding Command}">
<Button.ContentTemplate>
<DataTemplate>
<StackPanel>
<Image />
<TextBlock Text="{Binding DisplayName}" />
</StackPanel>
</DataTemplate>
</Button.ContentTemplate>
</Button>
上面的 xaml 是我试图用于项目模板的内容。
最佳答案
您必须绑定(bind) Image 控件的 Source
属性,类型为 ImageSource
.
WPF 具有来自 string
的内置类型转换, Uri
和 byte[]
至ImageSource
无需绑定(bind)转换器。
只要您的图像可以从 URI 字符串或字节数组(包含编码的位图帧,例如 PNG)创建,您就可以选择您喜欢的属性类型。 string
可能是最简单的一个,但其他的也是完全合法的。
但是,当您的 ViewModel 动态创建图像时,ImageSource
(或派生类型)通常是不使用绑定(bind)转换器的更合适的选项。
关于wpf - 如何以 MVVM 样式进行图像绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19117498/