WPF Enums in XAML And Root Addressing For Images


By Robbe Morris
Printer Friendly Version
View My Articles

  

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 } }


Biography
Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of EggHeadCafe. Robbe enjoys scuba diving with the folks at wet-n-fla.

button
 
Article Discussion: WPF - Silverlight Enums in XAML And Root Addressing For Images
Robbe Morris posted at 04-Sep-08 08:02
Original Article

promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid