Posted by: Zeeshan Amjad | December 30, 2011

Dependency property in User Control


I came across a situation where I am suppose to use two user controls to display the collection and their detail information using MVVM. Let’s make things simple and first try to use it without MVVM. For simplicity we are going to use only one user control and do not use MVVM.

Let’s make a user control first. This user control is a combination of list box and one text box at the top of list box to display the selected item in the list box.  Here is XAML for our user control.

Code Snippet
<UserControl x:Class="WpfUserControlList.CustomizedList"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <DockPanel>
        <TextBlock Margin="5" DockPanel.Dock="Top" Foreground="Yellow" FontSize="24"
                   Text="{Binding ElementName=list, Path=SelectedItem}">
            <TextBlock.Background>
                <LinearGradientBrush>
                    <GradientStop Offset="0" Color="Brown"/>
                    <GradientStop Offset="0.5" Color="LightYellow"/>
                    <GradientStop Offset="1" Color="Brown"/>
                </LinearGradientBrush>
            </TextBlock.Background>
               </TextBlock>
        <ListBox ItemsSource="{Binding}" x:Name="list" HorizontalContentAlignment="Stretch">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="2" BorderThickness="2" CornerRadius="3" BorderBrush="Brown">
                        <TextBlock Text="{Binding}" Margin="1">
                            <TextBlock.Background>
                                <LinearGradientBrush>
                                    <GradientStop Offset="0" Color="AliceBlue"/>
                                    <GradientStop Offset="1" Color="Blue"/>
                                </LinearGradientBrush>
                            </TextBlock.Background>
                        </TextBlock>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</UserControl>

 

Now let’s use our user control in our main program. Here is a XAML to use the user control in our main program.

Code Snippet
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <local:CustomizedList x:Name="uc" Margin="5" Grid.Column="0" DataContext="{Binding}" />
    <TextBlock Margin="5" Grid.Column="1"/>
</Grid>

 

Now if we want to display the selected item in the list box in the main text box, we can’t do it easily right now. One possible solution, if we are using MVVM, is to create one property and assign the selected item to it. Although that approach works but it is not a good design. The reason is that if we want to use this user control in any other project, then we have to do the same thing again and again. The better approach is to introduce one dependency property in the user control.

Here is a code to introduced a dependency property named SelectedItem in our user control. We set this property in the SelectionChanged event of the list box. Here is complete C# code of the program.

Code Snippet
using System.Windows;
using System.Windows.Controls;

namespace WpfUserControlList
{
    /// <summary>
    /// Interaction logic for CustomizedList.xaml
    /// </summary>
    public partial class CustomizedList : UserControl
    {
        public static readonly DependencyProperty SelectedItemProperty =
            DependencyProperty.Register("SelectedItem", typeof(string), typeof(CustomizedList));

        public string SelectedItem
        {
            get { return (string)GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }

        public CustomizedList()
        {
            InitializeComponent();
        }

        private void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SelectedItem = list.SelectedItem as string;
        }
    }
}

 

Here is complete XAML code of our user control.

Code Snippet
<UserControl x:Class="WpfUserControlList.CustomizedList"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008&quot;
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <DockPanel>
        <TextBlock Margin="5" DockPanel.Dock="Top" Foreground="Yellow" FontSize="24"
                   Text="{Binding ElementName=list, Path=SelectedItem}">
            <TextBlock.Background>
                <LinearGradientBrush>
                    <GradientStop Offset="0" Color="Brown"/>
                    <GradientStop Offset="0.5" Color="LightYellow"/>
                    <GradientStop Offset="1" Color="Brown"/>
                </LinearGradientBrush>
            </TextBlock.Background>
               </TextBlock>
        <ListBox ItemsSource="{Binding}" x:Name="list" HorizontalContentAlignment="Stretch" SelectionChanged="list_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border Margin="2" BorderThickness="2" CornerRadius="3" BorderBrush="Brown">
                        <TextBlock Text="{Binding}" Margin="1">
                            <TextBlock.Background>
                                <LinearGradientBrush>
                                    <GradientStop Offset="0" Color="AliceBlue"/>
                                    <GradientStop Offset="1" Color="Blue"/>
                                </LinearGradientBrush>
                            </TextBlock.Background>
                        </TextBlock>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</UserControl>

 

Now it we can easily do binding of the selected item of our user control with text box. Here is our XAML to do the binding.

Code Snippet
<TextBlock Margin="5" Grid.Column="1" Text="{Binding ElementName=uc, Path=SelectedItem}" />

 

Here is complete XAML code of our program.

Code Snippet
<Window x:Class="WpfUserControlList.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:WpfUserControlList"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <local:CustomizedList x:Name="uc" Margin="5" Grid.Column="0" DataContext="{Binding}" />
        <TextBlock Margin="5" Grid.Column="1" Text="{Binding ElementName=uc, Path=SelectedItem}" />
    </Grid>
</Window>

 

And here is complete C# code of the program.

Code Snippet
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfUserControlList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<string> states = new ObservableCollection<string>();

        public MainWindow()
        {
            InitializeComponent();

            states.Add("Maryland");
            states.Add("California");
            states.Add("Washington");
            states.Add("Virginia");
            states.Add("Florida");

            DataContext = states;
        }
    }
}

 

This is the output of the program.

UserControlList

Advertisements

Responses

  1. […] between user controls: Part 1 We saw one example of user control with dependency property here. Now we are going to introduce one more  user control and see how they communicate with each […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: