WPF Enums in XAML And Root Addressing For Images

This small code sample demonstrates how to use Enum values in your XAML files. It also includes how to set the image source property in your xaml files to image resources in different assemblies such as the BusinessLogic assembly in this sample.

If your application plans on storing XAML externally from your app and offer extreme styling flexibility to your users, then being able to set icons for various controls is likely to be a requirement for you.  So, just for kicks, I figured I show this quick tip demonstrating how to work with enums in your XAML.


  Download Source Code


<Window x:Class="WPFTutorial.Window1"
    
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    
xmlns:enums="clr-namespace:BusinessLogic.Enums;assembly=BusinessLogic"
    
xmlns:data="clr-namespace:BusinessLogic;assembly=BusinessLogic"
    
Title="Window1" Height="518" Width="658" WindowStartupLocation="CenterScreen">
    
    <Window.Resources>
        
           <DataTemplate x:Key="ColumnHeader">
                              
                 <StackPanel Orientation="Horizontal">
                     <TextBlock Text="Candidate"  Margin="3,3,3,3"/>
                 </StackPanel>
                   
         </DataTemplate>
      
         <DataTemplate x:Key="Cell"  DataType="x:Type data:Candidate">
                                
        <StackPanel Orientation="Horizontal">
           <Image  x:Name="Icon" HorizontalAlignment="Right"  Margin="3,3,3,3"
  VerticalAlignment="Bottom" Width="16" Height="16"
                
Source="/BusinessLogic;component/graphics/icons/Republican.gif"
Stretch="Fill" Visibility="Collapsed"/>
                     <TextBlock Text="{Binding Path=CandidateName, Mode=OneWay}"
Margin="3,3,3,3"/>
                 </StackPanel>
                   
               <DataTemplate.Triggers>
                   <DataTrigger Binding="{Binding Path=PoliticalPartyType}">
                     <DataTrigger.Value>
                          <enums:PoliticalPartyTypes>
                              Unknown
                          </enums:PoliticalPartyTypes>
                     </DataTrigger.Value>
                      <Setter TargetName="Icon" Property="Visibility" Value="Hidden"/>
                 </DataTrigger>
                 <DataTrigger Binding="{Binding Path=PoliticalPartyType}">
                     <DataTrigger.Value>
                          <enums:PoliticalPartyTypes>
                              Republican
                          </enums:PoliticalPartyTypes>
                     </DataTrigger.Value>
                        <Setter TargetName="Icon" Property="Source"
Value="/BusinessLogic;component/graphics/icons/republican.gif"/>
                       <Setter TargetName="Icon" Property="Visibility" Value="Visible"/>
                 </DataTrigger>
                   <DataTrigger Binding="{Binding Path=PoliticalPartyType}">
                     <DataTrigger.Value>
                          <enums:PoliticalPartyTypes>
                              Democrat
                          </enums:PoliticalPartyTypes>
                     </DataTrigger.Value>
                        <Setter TargetName="Icon" Property="Source"
Value="/BusinessLogic;component/graphics/icons/democrat.gif"/>
                       <Setter TargetName="Icon" Property="Visibility" Value="Visible"/>
                 </DataTrigger>
                     <DataTrigger Binding="{Binding Path=PoliticalPartyType}">
                     <DataTrigger.Value>
                          <enums:PoliticalPartyTypes>
                              Conservative
                          </enums:PoliticalPartyTypes>
                     </DataTrigger.Value>
                        <Setter TargetName="Icon" Property="Source"
Value="/BusinessLogic;component/graphics/icons/republican.gif"/>
                       <Setter TargetName="Icon" Property="Visibility" Value="Visible"/>
                 </DataTrigger>
               </DataTemplate.Triggers>
         </DataTemplate>
      
        
    </Window.Resources>
    
    
         <ListView Name="ListTemplates" Width="Auto" Height="Auto"
VerticalAlignment="Stretch"  HorizontalAlignment="Stretch">
             <ListView.View>
               <GridView>
                   <GridViewColumn Header="Candidate Name"
HeaderTemplate="{StaticResource ColumnHeader}"
CellTemplate="{DynamicResource Cell}"  />
               </GridView>
              </ListView.View>
               <ListView.ItemContainerStyle>
                     <Style TargetType="{x:Type ListViewItem}">
                           <Setter Property="HorizontalContentAlignment"
Value="Stretch" />
                     </Style>
               </ListView.ItemContainerStyle>
             </ListView>
</Window>




// Code behind

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows.Threading;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using BusinessLogic;
using BusinessLogic.Enums;

namespace WPFTutorial
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window, INotifyPropertyChanged
    {
        public Window1()
        {
             InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
        }

        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            LoadCandidates();
            this.ListTemplates.ItemsSource = CandidateList;
        }

        private void LoadCandidates()
        {
            ObservableCollection<Candidate>  list = new ObservableCollection<Candidate>();
             list.Add(new Candidate(0, "2008", "Candidates", (int)PoliticalPartyTypes.Republican));
             list.Add(new Candidate(1, "John", "McCain", (int)PoliticalPartyTypes.Republican));
             list.Add(new Candidate(2, "Lord", "Obama", (int)PoliticalPartyTypes.Democrat));
             list.Add(new Candidate(3, "Robbe", "Morris", (int)PoliticalPartyTypes.Conservative));

             this.CandidateList = list;
        }

        private ObservableCollection<Candidate> _candidateList = null;
        public ObservableCollection<Candidate> CandidateList
        {
            get
            {
                 return _candidateList;
            }
            set
            {
                _candidateList = value;
                 OnPropertyChanged("CandidateList");
            }
        }

        private Candidate _selectedCandidate;
        public Candidate SelectedCandidate
        {
            get { return _selectedCandidate; }
            set
            {
                _selectedCandidate = value;

                 OnPropertyChanged("SelectedCandidate");
            }
        }
  
        public event PropertyChangedEventHandler PropertyChanged;

         protected void OnPropertyChanged(string propertyName)
        {
             if (PropertyChanged == null) { return; }
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
      

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLogic
{
    public class Candidate
    {

         public Candidate(int candidateID, string firstName, string lastName, int politicalPartyID)
        {
            _candidateID = candidateID;
            _firstName = firstName;
            _lastName = lastName;
            _politicalPartyTypeID = politicalPartyID;
        }

        private int _candidateID = 0;
        public int CandidateID
        {
            get { return _candidateID; }
            set { _candidateID = value; }
        }

         public string CandidateName
        {
            get { return FirstName + " " + LastName; }
        }

        private string _firstName = string.Empty;
        public string FirstName
        {
            get { return _firstName; }
            set { _firstName = value.Trim(); }
        }

        private string _lastName = string.Empty;
        public string LastName
        {
            get { return _lastName; }
            set { _lastName = value.Trim(); }
        }

        private int _politicalPartyTypeID = 0;
        public int PoliticalPartyTypeID
        {
            get { return _politicalPartyTypeID; }
            set { _politicalPartyTypeID = value; }
        }

         public Enums.PoliticalPartyTypes PoliticalPartyType
        {
            get { return (Enums.PoliticalPartyTypes)_politicalPartyTypeID; }
         }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLogic.Enums
{

    public enum PoliticalPartyTypes : int
    {
       Unknown = 0,
        Republican = 1,
        Democrat = 2,
        Conservative = 3
    }
    
}
By Robbe Morris   Popularity  (5568 Views)
Picture
Biography - Robbe Morris
Robbe has been a Microsoft MVP in C# since 2004. He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.  Robbe also loves to scuba dive and go deep sea fishing in the Florida Keys or off the coast of Daytona Beach. Microsoft MVP