AspBucket offers ASP.NET, C#, VB, Jquery, CSS, Ajax, SQL tutorials. It is the best place for programmers to learn

Friday, 7 October 2016

How to implement string path to Image Converter in WPF?

In this article I will discuss how to create Image converter from giving path. Please follow below steps to implement this functionality.
Step 1- Add a new class for converter

 public class ImageToSourceConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
      if (targetType == typeof(ImageSource))
       if (value is string)
          string str = (string)value;
          return new BitmapImage(new Uri(str, UriKind.RelativeOrAbsolute));
        else if (value is Uri)
         Uri uri = (Uri)value;
         return new BitmapImage(uri);
      return value;
     public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
       throw new NotImplementedException();

Step 2- Call that converter from view by bindings. Please check below code where I am passing image iconpath as a string. 

<Window x:Class="inventory.View.MainWindow"
        Title="Inventory" Height="600" Width="800" MouseLeftButtonDown="Drag_Window"   ShowInTaskbar="True" WindowStartupLocation="CenterScreen"  FontFamily="Georgia" Background="Transparent"  Style="{DynamicResource MainWindowStyle}" x:Name="window" TabIndex="0" Foreground="#FFFFFFFF">

        <Convertor:ImageToSourceConverter x:Key="ImageSourceConverter">
            <RowDefinition Height="*"/>
                 ItemsSource="{Binding YourSource}"                  
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding IconPath,Converter={StaticResource ImageSourceConverter}}" Width="25" />
                            <TextBlock Text="{Binding Name}" Padding="10"/>
That's it image will display on the layout.


Post a Comment

  • Popular Posts
  • Comments