0

Hi I've been looking at ways to dynamically change an image Uri in xaml and in my research came across the following answer, which has certainly given me hope that what I really want to do might just be possible. In the original question the questioner wanted to swap the image itself, in my case I want to swap the directory where the image is located.

So when one looks at the answer that @Clemens provided one ends up with an images source being bound to a dependency property that is dynamically set when the form loads.

What I'd like to know is whether it would be feasible to set the location part of the uri dynamically (as per the logic that @Clemens is advocating and then simply append the Image name in the actual binding statement so that it might look something like this:

<Image Source="{Binding ImageUri & myImage.png}"/>

Essentially I have a number of buttons to which I would like to assign a default image og a size to be determined by the end user. To that end the Images would be stored in different folders in the application (in fact its a custom control) and then the relevant path bit of the URI would be set as per the suggestion in the referenced answer and I'd just append the Image name (which would be the same for the button irrespective of the size) and it would then have the correct image to display.

Community
  • 1
  • 1
Dom Sinclair
  • 2,458
  • 1
  • 30
  • 47

1 Answers1

0
  1. MainWindow.xaml.cs :

    namespace MainWindowNamespace
    {
         public sealed class ImageConverter : IValueConverter
         {
              public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
              {
                  try
                  {
                      string fullPath = Path.GetFullPath((string)value);
                      return new BitmapImage(new Uri(fullPath));
                  }
                  catch { return null; }
              }
    
              public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
              { throw new NotImplementedException(); }
         }
    }
    
  2. MainWindow.xaml :

    <Window  
       xmlns:imgConvert="clr-namespace:MainWindowNamespace">
    
      <Window.Resources>
          <imgConvert:ImageConverter x:Key="ImageConverter" />
      </Window.Resources>
    
      <Image ImageSource="{Binding ImagePath, Converter={StaticResource ImageConverter}}" />
    
    </Window>