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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModel="clr-namespace:inventory.ViewModel"
        xmlns:Convertor="clr-namespace:inventory.Converters"
        xmlns:View="clr-namespace:inventory.View"
        Icon="./../Files/inventory-icon.png"
        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">

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

0 comments :

Post a Comment

  • Popular Posts
  • Comments