Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image using trigger WPF MVVM

Tags:

c#

mvvm

wpf

xaml

This may be a no brainier but I just can't seem to get it to work. I have a view model that exposes a property called bool NotFound I would like to bind that to a trigger so that when it changes an image on my control changes.

This is the xaml that I am using as a data template for one of my view models.

<DataTemplate DataType="{x:Type local:TabFileViewModel}">
        <StackPanel Orientation="Horizontal">
              <Image Width="16" Height="16" Margin="3,0" Source="Image\TabFile.PNG" />
              <TextBlock Text="{Binding Name}" ToolTip="{Binding FullPath}"/>
       </StackPanel>
</DataTemplate>

I would like to be able to bind the to the NotFound property and change the image source.

like image 756
Nathan W Avatar asked Nov 23 '09 22:11

Nathan W


2 Answers

It's all good I figured it out.

<DataTemplate DataType="{x:Type local:TabFileViewModel}">
       <StackPanel Orientation="Horizontal">
         <Image Width="16" Height="16" Margin="3,0">
             <Image.Style>
                 <Style TargetType="{x:Type Image}">
                 <Style.Triggers>
                      <DataTrigger Binding="{Binding NotFound}" Value="false">
                          <Setter Property="Source" Value="Image\TabFile.PNG"/>
                      </DataTrigger>
                      <DataTrigger Binding="{Binding NotFound}" Value="true">
                          <Setter Property="Source" Value="Image\ErrorTabFile.PNG"/>
                      </DataTrigger>
                   </Style.Triggers>
              </Style>
           </Image.Style>
     </Image>
</DataTemplate> 
like image 156
Nathan W Avatar answered Nov 10 '22 08:11

Nathan W


<DataTemplate DataType="{x:Type local:TabFileViewModel}">
        <StackPanel Orientation="Horizontal">
              <Grid>
                  <Image x:Name="a" Width="16" Height="16" Margin="3,0" Source="Image\NotFounds.PNG" />
                  <Image x:Name="b" Width="16" Height="16" Margin="3,0" Source="Image\TabFile.PNG" />
                </Grid>
              <TextBlock Text="{Binding Name}" ToolTip="{Binding FullPath}"/>
       </StackPanel>
       <DataTemplate.Triggers>
            <DataTrigger Binding={Binding NotFound} Value="true">
                  <Setter TargetName="a" TargetProperty="Visibility" Value="Visible" />
                  <Setter TargetName="b" TargetProperty="Visibility" Value="Hidden" />
            </DataTrigger>
            <DataTrigger Binding={Binding NotFound} Value="false">
                  <Setter TargetName="a" TargetProperty="Visibility" Value="Hidden" />
                  <Setter TargetName="b" TargetProperty="Visibility" Value="Visible" />
            </DataTrigger>
       </DataTemplate.Triggers>
</DataTemplate>
like image 1
bitbonk Avatar answered Nov 10 '22 08:11

bitbonk