2

I want to use a dependency property so that my label displays values selected in the Listbox. This is just to more clearly understand the working of a dependency property.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WPFToolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
    xmlns:local="clr-namespace:WpfApplication1"
    x:Name="MyWindow"
    Height="200"
    Width="300">
       <StackPanel>
        <ListBox x:Name="lbColor"
                   Width="248"
                   Height="56"
                   ItemsSource="{Binding TestColor}"/>
       <StackPanel>
      <Label Content="{Binding Path=Test, ElementName=lbColor}" />
    </StackPanel>
  </StackPanel>
</Window>

Code Behind,

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

        public ObservableCollection<string> TestColor { get; set; }

        public String Test
        {
            get { return (String)GetValue(TestProperty); }
            set { SetValue(TestProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TestProperty =
            DependencyProperty.Register("Test", typeof(String), typeof(ListBox), new UIPropertyMetadata("Test1"));



        public Window1()
        {
            InitializeComponent();
            TestColor = new ObservableCollection<string>();
            DataContext = this;
            TestColor.Add("Red");
            TestColor.Add("Orange");
            TestColor.Add("Yellow");
            TestColor.Add("Green");
            TestColor.Add("Blue");
        }
    }
}

Can anyone explain to me how will I accomplish this using a dependency property? Somehow I am very confused with the Dependency Property concept, and I just wanted to see a working example for that.

Ehsan
  • 767
  • 7
  • 18
developer
  • 5,178
  • 11
  • 47
  • 72
  • For what you accomplish using Dependency Properties, look here: http://stackoverflow.com/questions/1723756/why-dependency-properties/1723831#1723831 – Kyle Rosendo Apr 19 '10 at 18:06
  • I do understand that there are a lot of examples out there showing DP and documentation related to why to use it, but I want to see something working, to make me understand what a DP does at what step. Like how is it invoked, at what point is the value set and what is the value that is being set and all.. – developer Apr 19 '10 at 18:20

2 Answers2

2

You'll need to have your ListBox "select" the current text:

<StackPanel>
    <!-- Add selected item binding -->
    <ListBox 
         x:Name="lbColor" Width="248" Height="56" 
         ItemsSource="{Binding TestColor}"
         SelectedItem="{Binding Test}"
    />

    <StackPanel>
        <!-- No need for elementname - just use Test on the DataContext -->
        <Label Content="{Binding Path=Test}" />
    </StackPanel>
</StackPanel>
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 1
    The above code works after I change the typeof Dependency Property from ListBox to Window1. Sir, can you explain me what technically exactly happens. I mean, does the value of the DP set after I click on the listbox values. And do I have to set the value of a DP to some source whenever I want to use a DP in the XAML, like we did over here?? – developer Apr 19 '10 at 18:47
  • 1
    Oh, yeah - I missed that wasn't set that way. You need to have the DependencyProperty type set to your class - since you're defining the DP on your class, not on the listbox. Right now, what's happening is that, when you select a new item (in the list box), the list box sets the "SelectedItem" value via binding back to your Window1 class. The label reflects the new value of the property, since it's a DP, and it updates itself. – Reed Copsey Apr 19 '10 at 18:52
2

I like to think of Data Binding as Big Brother. The Binding system sets itself up to watch all of its various registered Bindings and when the proper criteria have occurred (for example, FocusLost or PropertyChanged), the Binding system copies the source value to the target. For a TwoWay or OneWayToSource binding, the Binding system will even copy from the target to the source, if the right criteria happen.

The target has to be a DependencyProperty, as this is a special kind of property that knows how to Depend on other values. What the XAML {Binding} is doing under the covers is creating a new BindingExpression and then calling BindingOperations.SetBinding, which registers a particular BindingExpression with the Binding System, so it knows how to watch and perform the updates.

The advantage of this is that neither the target nor the source needs to take the responsibility for writing code to explicitly update the other. If I have code that knows how to provide a list of Colors, why should I care how the Colors get represented to the user? Because the Binding System takes care of the binding, it doesn't matter to me if the target using my Colors is a listbox, a treeview, or any other object that knows how to handle a list of items. I can focus on what I care about (the public interface I'm exposing) and don't have to care about the messy details of gluing that interface to something else.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102