Home > Software engineering >  How to dynamically "switch" StaticResource from ViewModel?
How to dynamically "switch" StaticResource from ViewModel?

Time:02-18

<Window.Resources>        
     <StackPanel Orientation="Horizontal" x:Key="disconnected">
         <Image Source="images/rpidisconnected.png" Width="20"/>
         <TextBlock Text="Disconnect" Margin="2 2 0 0"/>
     </StackPanel>
     <StackPanel Orientation="Horizontal" x:Key="connected">
         <Image Source="images/rpiconnected.png" Width="20"/>
         <TextBlock Text="Connect" Margin="2 2 0 0"/>
     </StackPanel>
</Window.Resources>

How to dynamically switch between "disconnected" and "connected" from ViewModel for the button control below?

<Button Width="100" Content="{StaticResource disconnected}"/>

CodePudding user response:

can be done via Style with trigger:

<Button Width="100">
 <Button.Style>
  <Style TargetType="Button">
   <Setter Property="Content" Value="{StaticResource disconnected}"/>
   <Style.Triggers>
    <DataTrigger Binding="{Binding IsConnectedViewModelBoolProperty}" Value="True">
     <Setter Property="Content" Value="{StaticResource connected}"/>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </Button.Style>
</Button>

or simpler with Style for Image:

<Button Width="100">
 <StackPanel Orientation="Horizontal">
  <Image Width="20">
   <Image.Style>
    <Style TargetType="Image">
     <Setter Property="Source" Value="images/rpidisconnected.png"/>
     <Style.Triggers>
      <DataTrigger Binding="{Binding IsConnectedViewModelBoolProperty}" Value="True">
       <Setter Property="Source" Value="images/rpiconnected.png"/>
      </DataTrigger>
     </Style.Triggers>
    </Style>
   </Image.Style>
  </Image>
  <TextBlock Text="Connect" Margin="2 2 0 0"/>
 </StackPanel>
</Button>
  • Related