If the binding source property-name varies, make a UserControl
or CustomControl
or as commanderz wrote, a ValueConverter
.
The following example shows how to create a UserControl:
<UserControl ..... />
<Image>
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding Status,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" Value="False">
<Setter Property="Source" Value="Images/cross.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=UserControl}}" Value="True">
<Setter Property="Source" Value="Images/check.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</UserControl>
In the code behind, create a dependency-property Status.
public partial class MyUserControl : UserControl {
public bool Status {
get { return (bool)GetValue(StatusProperty); }
set { SetValue(StatusProperty, value); }
}
public static readonly DependencyProperty StatusProperty = DependencyProperty.Register("Status", typeof(bool), typeof(MyUserControl), new UIPropertyMetadata(false));
public MyUserControl() {
InitializeComponent();
}
}
Then you can use the user-control anyway and just bind to the status-property:
<local:MyUserControl Status="{Binding Status}"/>
<local:MyUserControl Status="{Binding AnotherNamedStatusProperty}"/>
If the name of the binding-property is always the same, declare the style more global and set it then for each Image you want. E.g. put the style in the Window.Resources
-section and define a key for it (e.g. YourStyleKey_Style
);
<Window.Resources>
<Style TargetType="{x:Type Image}" x:Key="YourStyleKey_Style">
<Style.Triggers>
<DataTrigger Binding="{Binding Status}" Value="False">
<Setter Property="Source" Value="Images/cross.png"/>
</DataTrigger>
<DataTrigger Binding="{Binding Status}" Value="True">
<Setter Property="Source" Value="Images/check.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
In your xaml where you need such an image, declare an image and set the Style through the Style
-attribute.
<Image Style="{StaticResource YourStyleKey_Style}"