How to declare combobox itemTemplate that has Itemsource as Enum Values in WPF?
Asked Answered
D

1

8

I have a enum let's say

enum MyEnum
{
  FirstImage,
  SecondImage,
  ThirdImage,
  FourthImage
};

I have binded this Enum to my combobox in XAML.

While defining an combobox I have defined an ItemTemplate of combox to take Two UI element:

  1. TextBlock that show the enum value (Description)
  2. Image

I have done this much in XAML.

I am wondering where I can specify the Image corrosponding to each item of Enum value in a combobox? Is that possible through data trigger ?

I really appreciate if anyone have the XAML for this scenario.

Many Thanks in advance

Distortion answered 28/3, 2010 at 12:29 Comment(0)
P
14

You can use a DataTrigger, but would be more maintainable if you used a Converter. Here's a sample that uses a DataTrigger for a view of the image and text by itself, and then the same DataTrigger to display the image and text in ListBox and ComboBox, and finally, a ListBox and ComboBox that use a Converter to display the image and text:

XAML

<Window x:Class="WpfSandbox.EnumToImage.EnumToImage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfSandbox.EnumToImage"
        Title="Enum To Image" SizeToContent="WidthAndHeight"  >

    <Window.DataContext>
        <local:ImageViewModel x:Name="Model" />
    </Window.DataContext>

    <Window.Resources>

        <ObjectDataProvider x:Key="EnumDataProvider" 
                            MethodName="GetValues" 
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:Decade"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

        <local:DecadeEnumImageConverter x:Key="ImageConverter" />


        <ControlTemplate x:Key="ImageTemplate" >

            <StackPanel Orientation="Horizontal">
                <Image x:Name="MyImage" Width="64" Height="32" />
                <TextBlock Text="{Binding}" VerticalAlignment="Center"  />
            </StackPanel>


            <ControlTemplate.Triggers>
                <DataTrigger Binding="{Binding}" Value="Ninties" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/90s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
                <DataTrigger Binding="{Binding}" Value="Eighties" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/80s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
                <DataTrigger Binding="{Binding}" Value="Seventies" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/70s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
                <DataTrigger Binding="{Binding}" Value="Sixties" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/60s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
                <DataTrigger Binding="{Binding}" Value="Fifties" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/50s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
                <DataTrigger Binding="{Binding}" Value="Forties" >
                    <DataTrigger.Setters>
                        <Setter TargetName="MyImage" 
                                Property="Source" 
                                Value="/EnumToImage/images/40s.jpg"/>
                    </DataTrigger.Setters>
                </DataTrigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>

        <DataTemplate x:Key="ItemsTemplateWithConverter">
            <StackPanel Orientation="Horizontal">
                <Image Width="64" Height="32"  
                       Source="{Binding Converter={StaticResource ImageConverter}}"/>
                <TextBlock Text="{Binding}" VerticalAlignment="Center"  />
            </StackPanel>
        </DataTemplate>

        <DataTemplate x:Key="ItemsTemplateWithDataTrigger">
            <ContentControl Template="{StaticResource ImageTemplate}" />
        </DataTemplate>

    </Window.Resources>


    <StackPanel>
        <ContentControl Margin="10" MouseUp="OnImageMouseUp"
                        HorizontalAlignment="Center" Cursor="Hand"
                        DataContext="{Binding Path=ImageEnum}"
                        Template="{StaticResource ImageTemplate}" />

        <StackPanel Orientation="Horizontal">

            <StackPanel>
                <ListView Margin="10" 
                  ItemsSource="{Binding Source={StaticResource EnumDataProvider}}" 
                  ItemTemplate="{StaticResource ItemsTemplateWithConverter}" />

                <ComboBox Margin="10" 
                  ItemsSource="{Binding Source={StaticResource EnumDataProvider}}" 
                  ItemTemplate="{StaticResource ItemsTemplateWithConverter}" />
            </StackPanel>

            <StackPanel>
                <ListView Margin="10" 
                  ItemsSource="{Binding Source={StaticResource EnumDataProvider}}" 
                  ItemTemplate="{StaticResource ItemsTemplateWithDataTrigger}" />

                <ComboBox Margin="10" 
                  ItemsSource="{Binding Source={StaticResource EnumDataProvider}}" 
                  ItemTemplate="{StaticResource ItemsTemplateWithDataTrigger}" />
            </StackPanel>

        </StackPanel>
    </StackPanel>

</Window>

Code Behind

using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Data;

namespace WpfSandbox.EnumToImage
{
    /// <summary>
    /// Interaction logic for EnumToImage.xaml
    /// </summary>
    public partial class EnumToImage : Window
    {
        public EnumToImage()
        {
            InitializeComponent();
        }

        private int i = 1;
        private void OnImageMouseUp( object sender, MouseButtonEventArgs e )
        {
            i++;
            Model.ImageEnum = ( Decade )i;

            if( i == 6 )
                i = 0;
        }
    }

    public enum Decade
    {
        Ninties = 1,
        Eighties = 2,
        Seventies = 3,
        Sixties = 4,
        Fifties = 5,
        Forties = 6,
    };

    public class ImageViewModel : INotifyPropertyChanged
    {
        private Decade _imageEnum;
        public Decade ImageEnum
        {
            get { return _imageEnum; }
            set
            {
                _imageEnum = value;
                RaisePropertyChanged( "ImageEnum" );
            }
        }

        public ImageViewModel()
        {
            ImageEnum = Decade.Ninties;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void RaisePropertyChanged( string propertyName )
        {
            var handler = PropertyChanged;
            if( handler != null )
            {
                handler( this, new PropertyChangedEventArgs( propertyName ) );
            }
        }

    }

    public class DecadeEnumImageConverter : IValueConverter
    {
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
        {

            var myEnum = ( Decade )Enum.Parse( typeof( Decade ), value.ToString() );

            switch( myEnum )
            {
                case Decade.Ninties:
                    return "/EnumToImage/images/90s.jpg";
                case Decade.Eighties:
                    return "/EnumToImage/images/80s.jpg";
                case Decade.Seventies:
                    return "/EnumToImage/images/70s.jpg";
                case Decade.Sixties:
                    return "/EnumToImage/images/60s.jpg";
                case Decade.Fifties:
                    return "/EnumToImage/images/50s.jpg";
                case Decade.Forties:
                    return "/EnumToImage/images/40s.jpg";
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )
        {
            throw new NotImplementedException();
        }
    }
}
Praxis answered 28/3, 2010 at 18:42 Comment(1)
Many Many Thanks for the solution for both using Converters and Data Triggers. I do agree with you that using converter will be more maintainable.Distortion

© 2022 - 2024 — McMap. All rights reserved.