且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVVM中的WPF databind Image.Source

更新时间:2023-11-10 22:59:34

您可以使用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.