MVVM中的WPF databind Image.Source [英] WPF databind Image.Source in MVVM
问题描述
要明确的说,希望我的ViewModel知道具体的图像(这是为了了解),只是触发不同图像的状态。现在我只有两个州,让我们说红色和绿色。我应该创建一个枚举属性还是一个布尔?然后我如何数据绑定来切换图像源?
您可以使用DataTrigger,并更改图像XAML)基于ViewModel中属性的值。我个人会使用一个枚举,因为你可能需要多个状态。
VisualStateManager也可以为此工作,但需要WPF Futures或.NET 4。 / p>
为了使用DataTrigger,您可以执行以下操作:
< Image>
< Image.Style>
< Style TargetType =Image>
< Setter Property =SourceValue =1.png/>
< Style.Triggers>
< DataTrigger Binding ={Binding ViewModelEnumProperty}Value =Image2>
< Setter Property =SourceValue =2.png/>
< / DataTrigger>
< /Style.Triggers>
< / Style>
< /Image.Style>
< / Image>
这将使用1.png,但是当您的枚举设置为Image2时VM,它会切换到2.png。更多DataTriggers可以根据需要添加。
I'm using MVVM and am trying to databind the Source property of Image to my ViewModel in such a way that I can change the icon on the fly. What is the best pattern to follow for this? I still have the flexibility to change my ViewModel to suit, but I don't know where to start in either the xaml or ViewModel.
To be clear, I don't want my ViewModel to know about the specific images (that's for the View to know), just the state that triggers different images. For now I have just two states, lets say Red and Green. Should I create an Enum property or a bool? And then how do I databind to switch the image source?
You can use a DataTrigger, and change the image (entirely in XAML) based on the value of a property in your ViewModel. I, personally, would use an enum, since you may want multiple states.
VisualStateManager will work for this as well, but will require WPF Futures or .NET 4.
In order to use a DataTrigger, you can do something like:
<Image>
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="1.png" />
<Style.Triggers>
<DataTrigger Binding="{Binding ViewModelEnumProperty}" Value="Image2">
<Setter Property="Source" Value="2.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
This will use "1.png", but when your enum is set to "Image2" in the VM, it'd switch to 2.png. More DataTriggers can be added as needed.
这篇关于MVVM中的WPF databind Image.Source的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!