WPF: Binding to a collection

This entry is part 39 of 54 in the series Learn WPF

Using the ListBox, we show another example on how we can bind a class’s properties to a collection.

ListBox is one of those controls that can display multiple data objects.  With the help of data templates and value converters, it can become a powerful visualization tool.

MainWindow.xaml
<Window x:Class="ListBoxBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="lb">
        </ListBox>
    </Grid>
</Window>

MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;

namespace ListBoxBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        List<Person> people = new List<Person> {
              new Person { Name = "Michelle", Age = 10 },
              new Person { Name = "Emily", Age = 45 },
              new Person { Name = "John", Age = 35 },
              new Person { Name = "Lisa", Age = 12 },
              new Person { Name = "Maggie", Age = 1 }
            };

        public MainWindow()
        {
            InitializeComponent();
            lb.ItemsSource = people;
        }
    }
}

Person.cs
namespace ListBoxBinding
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return string.Format("{0} is {1} years old", Name, Age);
        }
    }
}

collectionbinding

 

 

 

 

 

WPF: Combobox binding

This entry is part 27 of 54 in the series Learn WPF

In Windows Desktop, ComboBox works just like a drop down list in the web.

Here we illustrate an example where the background color of a canvas is bound to a ComboBox selection.

In this example, I have also used setter property to style the TextBlock, Canvas etc.  This is just like using CSS to style a HTML page.

MainWindow.xaml
<Window x:Class="BindControls.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    
        <Window.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="FontSize" Value="16"/>
                <Setter Property="FontWeight" Value="Bold"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>
                <Setter Property="HorizontalAlignment" Value="Center"/>
            </Style>
            <Style TargetType="Canvas">
                <Setter Property="Height" Value="150"/>
                <Setter Property="Width" Value="150"/>
                <Setter Property="Margin" Value="8"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>
            </Style>
            <Style TargetType="ComboBox">
                <Setter Property="Width" Value="60"/>
                <Setter Property="Margin" Value="8"/>
                <Setter Property="DockPanel.Dock" Value="Top"/>
            </Style>
        </Window.Resources>

        <Border Margin="10" BorderBrush="Silver" BorderThickness="3" Padding="8">
            <DockPanel>
                <TextBlock>Choose a Color:</TextBlock>
            <ComboBox Name="myBox" SelectedIndex="0">
                <ComboBoxItem>Green</ComboBoxItem>
                <ComboBoxItem>Blue</ComboBoxItem>
                <ComboBoxItem>Red</ComboBoxItem>
            </ComboBox>
            <Canvas Background="{Binding ElementName=myBox, Path=SelectedItem.Content}"></Canvas>
            </DockPanel>
        </Border>
    
</Window>

MainWindow.xaml.cs
using System.Windows;

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

When you run the code and changing the ComboBox selection, the canvas color will change according to the selection.  This is done mainly with xaml.

The main line that is performing this trick is:

<Canvas Background="{Binding ElementName=myBox, Path=SelectedItem.Content}"></Canvas>

Each change in the ComboBox selection will update the background color as we have set the Path to SelectedItem.Content of the combo box.

combobox

 

 

WPF: Binding slider and textbox

This entry is part 23 of 54 in the series Learn WPF

When we move the slider, we can have the text in the TextBox updated accordingly.

Using a two-way mode, when we update the value in the TextBox, we can have the slider to move according to the value in the TextBox too.

In the previous example, when we move the slider, the font size changes accordingly.  This behaviour is actually controlled by UpdateSourceTrigger property.  As we did not specify its value, it is in its default state which then depends on the source that it is bound to.

The default value for most properties is PropertyChanged, while the Text property has a default value of LostFocus.

The example below best illustrate the LostFocus property of a slider which in this case is the source.  The TextBox is the target.

MainWindow.xaml
<Window x:Class="SliderName.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <TextBox Text="{Binding Path=Value, ElementName=slider, UpdateSourceTrigger=LostFocus, Mode=TwoWay}" Grid.Row="0" FontSize="20" MaxWidth="50"/>
        <Slider x:Name="slider" Grid.Row="1" Minimum="10" Maximum="80" Value="30" IsSnapToTickEnabled="True"/>
    </Grid>
</Window>

slidertextbox

If you click on the slider and move along the line, the value in the textbox will change accordingly.

In this example, we also have a two-way mode binding and a LostFucus value in UpdateSourceTrigger.  If you change the value in the TextBox and click the mouse pointer not on the slider but right below the slider simulating a lost focus click, the slider will move depending on the value in the TextBox.