#968 – ListBox Data Binding Basics, part V

If you want to display the items in a ListBox using something more than a simple string, you can set the ItemTemplate of the ListBox and define the exact layout of each item.  When you set the ItemTemplate, you don’t set the DisplayMemberPath property.  DisplayMemberPath simple defines the template for each item in the ListBox to be a TextBlock that displays a single string.

In the example below, we set an item template for a ListBox that binds to a collection of Actor objects so that we display an image and some information about the actor, for each item.

        <ListBox Margin="15" Width="250" Height="250"
                 ItemsSource="{Binding ActorList}"
                 SelectedItem="{Binding SelectedActor}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Source="{Binding Image}" Height="80"/>
                        <StackPanel Margin="5">
                            <TextBlock Text="{Binding FullName}" FontSize="12" FontWeight="Bold"/>
                            <TextBlock Text="{Binding Dates}"/>
                            <TextBlock Text="{Binding KnownFor}" Margin="0,5,0,0" FontStyle="Italic"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

968-001

#967 – ListBox Data Binding Basics, part IV

In the earlier posts, we created an Actor class and then populated a list with a series of Actor objects.  We can now bind a ListBox to this list using its ItemsSource property.

    <StackPanel>
        <ListBox Margin="15" Width="250" Height="250"
                 ItemsSource="{Binding ActorList}"
                 DisplayMemberPath="NameAndDates"
                 SelectedItem="{Binding SelectedActor}"/>
        <Label Margin="10,0" Content="{Binding SelectedActor.KnownFor}"/>
    </StackPanel>

The ItemsSource property indicates that we want the ListBox filled with elements from our ActorList property, which is a collection of Actor objects.

The DisplayMemberPath property indicates that each entry in the list should be rendered as a string using the Actor.NameAndDates property.

The SelectedItem property indicates that when a user selects an item, our SelectedActor property should be set to refer to the selected Actor instance.  We demonstrate that by binding a Label element to a property of that selected actor.

967-001

#966 – ListBox Data Binding Basics, part III

Assume that we want to use a ListBox to display a list of actors and that we have an Actor type to store all the information for a single actor.

Our next step is to create a collection of Actor instances that we’ll then be able to bind to.  Below is the code-behind for a simple WPF application that creates a collection of Actor instances and stores them in an ActorList property.  We also set up a SelectedActor property that will use data binding to reflect the actor that the user has currently selected.

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;

            ActorList = new ObservableCollection<Actor>
            {
                new Actor("Ginger Rogers", 1911, 1995, "Kitty Foyle",
                    new Uri("ActressImages/GingerRogers.jpg", UriKind.Relative)),
                new Actor("Joan Fontaine", 1917, null, "Suspicion",
                    new Uri("ActressImages/JoanFontaine.jpg", UriKind.Relative)),
                new Actor("Greer Garson", 1904, 1996, "Mrs. Miniver",
                    new Uri("ActressImages/GreerGarson.jpg", UriKind.Relative)),
                new Actor("Jennifer Jones", 1919, 2009, "The Song of Bernadette",
                    new Uri("ActressImages/JenniferJones.jpg", UriKind.Relative)),
                new Actor("Ingrid Bergman", 1915, 1982, "Gaslight",
                    new Uri("ActressImages/IngridBergman.jpg", UriKind.Relative)),
                new Actor("Joan Crawford", 1904, 1977, "Mildred Pierce",
                    new Uri("ActressImages/JoanCrawford.jpg", UriKind.Relative)),
                new Actor("Olivia de Havilland", 1916, null, "To Each His Own",
                    new Uri("ActressImages/OliviaDeHavilland.jpg", UriKind.Relative)),
                new Actor("Loretta Young", 1913, 2000, "The Farmer's Daughter",
                    new Uri("ActressImages/LorettaYoung.jpg", UriKind.Relative)),
                new Actor("Jane Wyman", 1917, 2007, "Johnny Belinda",
                    new Uri("ActressImages/JaneWyman.jpg", UriKind.Relative)),
                new Actor("Judy Holliday", 1921, 1965, "Born Yesterday",
                    new Uri("ActressImages/JudyHolliday.jpg", UriKind.Relative))
            };
        }

        private ObservableCollection<Actor> actorList;
        public ObservableCollection<Actor> ActorList
        {
            get { return actorList; }
            set
            {
                if (value != actorList)
                {
                    actorList = value;
                    RaisePropertyChanged("ActorList");
                }
            }
        }

        private Actor selectedActor;
        public Actor SelectedActor
        {
            get { return selectedActor; }
            set
            {
                if (value != selectedActor)
                {
                    selectedActor = value;
                    RaisePropertyChanged("SelectedActor");
                }
            }
        }

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

#965 – ListBox Data Binding Basics, part II

Assume that we want to use a ListBox to display a list of actors.  We can start by creating an Actor type that stores various information about an actor.  We want the class to implement the INotifyPropertyChanged interface, so that data binding client are notified of changes to any properties.

Full code for Actor.cs is shown below.  Note that when we change FullName, BirthYear or DeathYear properties, we also flag the derived NameAndDates property as potentially changed.

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

namespace WpfApplication2
{
    public class Actor : INotifyPropertyChanged
    {
        public Actor()
        {
        }

        public Actor(string fullName, int? birthYear, int? deathYear, string knownFor, Uri image)
        {
            FullName = fullName;
            BirthYear = birthYear;
            DeathYear = deathYear;
            KnownFor = knownFor;
            Image = image;
        }

        private string fullName;
        public string FullName
        {
            get { return fullName; }
            set
            {
                fullName = value;
                RaisePropertyChanged("FullName");
                RaisePropertyChanged("NameAndDates");
            }
        }

        private int? birthYear;
        public int? BirthYear
        {
            get { return birthYear; }
            set
            {
                birthYear = value;
                RaisePropertyChanged("BirthYear");
                RaisePropertyChanged("NameAndDates");
            }
        }

        private int? deathYear;
        public int? DeathYear
        {
            get { return deathYear; }
            set
            {
                deathYear = value;
                RaisePropertyChanged("DeathYear");
                RaisePropertyChanged("NameAndDates");
            }
        }

        private string knownFor;
        public string KnownFor
        {
            get { return knownFor; }
            set
            {
                knownFor = value;
                RaisePropertyChanged("KnownFor");
            }
        }

        private Uri image;
        public Uri Image
        {
            get { return image; }
            set
            {
                image = value;
                RaisePropertyChanged("Image");
            }
        }

        public string NameAndDates
        {
            get
            {
                string result = FullName;

                if (BirthYear.HasValue)
                {
                    if (DeathYear.HasValue)
                        result = result + string.Format(" ({0}-{1})", BirthYear.Value, DeathYear.Value);
                    else
                        result = result + string.Format(" ({0}- )", BirthYear.Value);
                }

                return result;
            }
        }

        // INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}

#964 – ListBox Data Binding Basics, Part I

You can use data binding to load and manage the items displayed in a ListBox control.

You bind the ItemsSource property of the ListBox to a collection that implements the IEnumerable interface.  The collection bound to can contain any type of object.

If the ListBox is displaying simple strings, you can set the DisplayMemberPath property to the string-typed property of a bound object  that should be used to get the display string for each item.

You can also use binding to bind the SelectedItem property of the ListBox to a property whose type matches the types in the collection that ItemsSource binds to.  When the user selects an item in the ListBox, the corresponding property is updated to refer to the correct item.  And if the property bound to is changed from code-behind, the selected item in the ListBox changes.

Next time: Code sample for all of this.

#825 – Two Way Binding for a CheckBox

You can bind the IsChecked property of a CheckBox to a boolean variable, so that the variable will always reflect the current value of the CheckBox in the user interface.

You can also do two-way binding, where the boolean variable changes when the user toggles the CheckBox, but the CheckBox also toggles when the value of the variable changes.

        <Label Content="Things my dog can do:"/>
        <CheckBox Content="Sit" IsChecked="{Binding CanSit, Mode=TwoWay}"/>
        <CheckBox Content="Stay" IsChecked="{Binding CanStay, Mode=TwoWay}"/>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
            <Button Content="Report State" Click="btnReportState_Click"
                    Margin="5"/>
            <Button Content="Change State" Click="btnChangeState_Click"
                    Margin="5"/>
        </StackPanel>

Code-behind:

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private bool canSit;
        public bool CanSit
        {
            get { return canSit; }
            set
            {
                canSit = value;
                RaisePropertyChanged("CanSit");
            }
        }

        private bool canStay;
        public bool CanStay
        {
            get { return canStay; }
            set
            {
                canStay = value;
                RaisePropertyChanged("CanStay");
            }
        }

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;
        }

        private void btnReportState_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(string.Format("Sit: {0}, Stay: {1}", CanSit, CanStay));
        }

        private void btnChangeState_Click(object sender, RoutedEventArgs e)
        {
            CanSit = CanSit ? false : true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }

#635 – Using a Value Converter to Change User Input

Instead of modifying user input by handling the TextChanged event, you can use a value converter to change the text input.  Below, we bind the Text property of a TextBox to a string property and specify a converter, which will convert vowels to uppercase.

<Window x:Class="WpfApplication9.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication9"
        Title="TextChanged"
        Height="150" Width="400">

    <Window.Resources>
        <ResourceDictionary>
            <local:CapVowelsConverter x:Key="capVowelsConverter"/>
        </ResourceDictionary>
    </Window.Resources>

    <StackPanel Orientation="Vertical">
        <TextBox HorizontalAlignment="Center" Width="150" Margin="10"
                 Text="{Binding Path=MyText, Converter={StaticResource capVowelsConverter}, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="What Is My Text?" HorizontalAlignment="Center" Margin="10" Click="Button_Click"/>
    </StackPanel>
</Window>

Here’s the code for the value converter:

    public class CapVowelsConverter : IValueConverter
    {
        // From bound property TO the control -- no conversion
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        // To bound property FROM the control -- capitalize vowels
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string input = (string)value;

            const string vowels = "aeiou";

            StringBuilder sbInput = new StringBuilder(input);
            for (int i = 0; i < sbInput.Length; i++)
            {
                if (vowels.Contains(char.ToLowerInvariant(sbInput[i])))
                    sbInput[i] = char.ToUpper(sbInput[i]);
            }

            return sbInput.ToString();
        }
    }


#495 – Binding to a Visibility Property Without Using a Value Converter

You can use a value converter to convert a string value to a value of type System.Windows.Visibility, allowing data binding to a Visibility property.  You can also just set a Visibility property directly to a string, avoiding the need for a value converter.

In the example below, we bind to the Content property of a ComboBoxItem, which we access through the SelectedValue property of a ComboBox.  Since Content contains a string, the binding to Visibility works without a conversion.

    <StackPanel>
        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Snoopy" Margin="3" Background="BurlyWood"/>
            <Label Content="Waldo" Margin="3" Background="Thistle"
                   Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue.Content}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        </StackPanel>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
            <ComboBox.Items>
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>
            </ComboBox.Items>
        </ComboBox>
        <Label Content="Select visibility of middle Label" HorizontalAlignment="Center"/>
    </StackPanel>

#494 – Using a Value Converter to Bind to a Visibility Property

You can bind the Visibility property of a control to a data item whose type is System.Windows.Visibility.  You can also bind to an item whose type is string, provided that the string values returned represent one of the enumerated values from the Visibility type.

The example below shows how to use a value converter to convert from the SelectedValue of a ComboBox (a ComboBoxItem) to the Visibility type.

        <StackPanel Orientation="Horizontal" Margin="10">
            <Label Content="Snoopy" Margin="3" Background="BurlyWood"/>
            <Label Content="Waldo" Margin="3" Background="Thistle"
                   Visibility="{Binding ElementName=cboVisibility, Path=SelectedValue, Converter={StaticResource cboVisibilityConverter}}"/>
            <Label Content="Dagwood" Margin="3" Background="LightGreen"/>
        </StackPanel>
        <ComboBox Name="cboVisibility" HorizontalAlignment="Center" SelectedIndex="0">
            <ComboBox.Items>
                <ComboBoxItem Content="Visible"/>
                <ComboBoxItem Content="Collapsed"/>
                <ComboBoxItem Content="Hidden"/>
            </ComboBox.Items>
        </ComboBox>

Code for IValueConverter.Convert:

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Visibility visibility = Visibility.Visible;

            try
            {
                if (value != null)
                {
                    ComboBoxItem item = (ComboBoxItem)value;
                    visibility = (Visibility)Enum.Parse(typeof(Visibility), (string)item.Content, false);
                }
            }
            catch { }

            return visibility;
        }

#485 – Binding a ComboBox to an Enumerated Type’s List of Values

You can easily bind a ComboBox (or ListBox) to an enumerated type’s values using an ObjectDataProvider.  The ObjectDataProvider allows calling a method and then using the result of the method call as a binding source.

To get the list of values for an enumerated type, we call the Enum.GetValues method, passing in the specific enumerated type.  In the example below, we do this in an ObjectDataProvider.

    <Window.Resources>
        <ObjectDataProvider x:Key="dateTimeKindValues" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="sys:DateTimeKind"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>

(This assumes that we’ve defined the sys namespace):

    xmlns:sys="clr-namespace:System;assembly=mscorlib"

The ObjectDataProvider is equivalent to the following code:

            DateTimeKind[] values = (DateTimeKind[])Enum.GetValues(typeof(DateTimeKind));

We can now use the output of the ObjectDataProvider as a data source for our binding.

    <ComboBox Height="25" Width="150"
              ItemsSource="{Binding Source={StaticResource dateTimeKindValues}}"/>

This gives us a ComboBox that lists the possible values of the DateTimeKind enumerated type.

Follow

Get every new post delivered to your Inbox.

Join 312 other followers