XAML image source set dynamically based on content

Well, this is not very dynamic, at least it will not change at runtime.

The idea is that I have buttons, and each of them has a unique image (32x32 icon). All buttons have a style that I fiddled with ControlTemplate. Thus, each image also has 2 colors, one normal and another when I click.

I noticed that when I declare the original path for the images, it is that they are almost all the same, so I, although DRY (do not repeat it myself). What if I can use the Name button or some other property as part of the original path (i.e. the image file name). It will be good programming.

The problem is that I am new to XAML, WPF and maybe programming all together, so I'm not sure how to do this. I assume that this will require a code or some kind of converter (I think I will read a little more about converters). Here is some code (this does not work, but it gives you a general idea (hopefully)):

<Style x:Key="ButtonPanelBigButton" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Name="ButtonBorder"
                        Height="78"
                        MaxWidth="70"
                        MinWidth="50"
                        BorderThickness="0.5"
                        BorderBrush="Transparent"
                        CornerRadius="8" >
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="2*" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>

                        <!-- Here I wan't to put in the Name property of the button because there is a picture there to match -->
                        <Image x:Name="ButtonIcon" Source="..\Images\Icons\32x32\Blue\{Binding Name}.png" 

                               Margin="4"
                               Height="32"
                               Width="32"
                               HorizontalAlignment="Center" 
                               VerticalAlignment="Center" />

                        <TextBlock Grid.Row="1"
                                   Padding="5,2,5,2"
                                   TextWrapping="Wrap"
                                   Style="{StaticResource MenuText}"
                                   HorizontalAlignment="Center"
                                   VerticalAlignment="Center">
                            <ContentPresenter ContentSource="Content" />                
                        </TextBlock>
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True" >
                        <Setter TargetName="ButtonIcon" Property="Source" Value="..\Images\Icons\32x32\Green\user.png" /> <!-- Same Here -->
                        <Setter TargetName="ButtonBorder" Property="BorderBrush" Value="{StaticResource SecondColorBrush}" />
                        <Setter TargetName="ButtonBorder" Property="Background">
                            <Setter.Value>
                                <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1" Opacity="0.5">
                                    <GradientStop Color="{StaticResource MainColor}" Offset="1" />
                                    <GradientStop Color="{StaticResource SecondColor}" Offset="0.5" />
                                    <GradientStop Color="{StaticResource MainColor}" Offset="0" />
                                </LinearGradientBrush>
                            </Setter.Value>
                        </Setter>
                    </Trigger>
                </ControlTemplate.Triggers>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I hope you go where I am going and someone can help me, so my code is nice and dry (now I repeat !!!).

+3
source share
1 answer

You are right: an easy way to solve this is to use a converter.

The Source property uses ImageSource, so you will need to load the bitmap into the converter.

The converter is used as follows:

 <Image Source="{Binding Name,
                         RelativeSource={RelativeSource TemplatedParent},
                         Converter={x:Static local:ImageSourceLoader.Instance},
                         ConverterParameter=..\Images\Icons\32x32\Blue\{0}.png}" />

And implemented like this:

public class ImageSourceLoader : IValueConverter
{
  public static ImageSourceLoader Instance = new ImageSourceLoader();

  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var path = string.Format((string)parameter, value.ToString());
    return BitmapFrame.Create(new Uri(path, UriKind.RelativeOrAbsolute));
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

, Uris, BaseUri Image . Uris, , StringFormat:

 <Image local:ImageHelper.SourcePath="{Binding Name,
                         RelativeSource={RelativeSource TemplatedParent},
                         StringFormat=..\Images\Icons\32x32\Blue\{0}.png}" />

PropertyChangedCallback BaseUri Uri:

public class ImageHelper : DependencyObject
{
  public static string GetSourcePath(DependencyObject obj) { return (string)obj.GetValue(SourcePathProperty); }
  public static void SetSourcePath(DependencyObject obj, string value) { obj.SetValue(SourcePathProperty, value); }
  public static readonly DependencyProperty SourcePathProperty = DependencyProperty.RegisterAttached("SourcePath", typeof(string), typeof(ImageHelper), new PropertyMetadata
  {
    PropertyChangedCallback = (obj, e) =>
      {
        ((Image)obj).Source =
          BitmapFrame.Create(new Uri(((IUriContext)obj).BaseUri, (string)e.NewValue));
      }
  });
}
+2

Source: https://habr.com/ru/post/1752268/


All Articles