Click here to Skip to main content
15,867,686 members
Articles / Desktop Programming / WPF

WPF: Binding to Individual Collection Items (But Not in an ItemsControl)

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
17 Jun 2009CPOL 55.8K   154   5   5
Binding to individual collection items (but not in an ItemsControl) in WPF

Well, I had a great day yesterday, and quite a surprising one. I had an issue with an idea I was working on, so naturally I turned to Josh Smith.

And guess what I, yes me, the mere mortal managed to teach Josh something about WPF…Ha Ha, check that.

So here is what I taught Josh…..(still can't believe I managed to teach Josh something ;-) )

I want to be able to bind multiple controls that are all stand alone controls to a collection. Sounds simple enough, right.

Check this code behind:

C#
 1:  using System;
 2:  using System.Collections.Generic;
 3:  using System.Collections.ObjectModel;
 4:  using System.Linq;
 5:  using System.Text;
 6:  using System.Windows;
 7:  using System.Windows.Controls;
 8:  using System.Windows.Data;
 9:  using System.Windows.Documents;
10:  using System.Windows.Input;
11:  using System.Windows.Media;
12:  using System.Windows.Media.Imaging;
13:  using System.Windows.Navigation;
14:  using System.Windows.Shapes;
15:
16:  namespace WPF_test
17:  {
18:      public partial class Window1 : Window
19:      {
20:          public ObservableCollection<string>
21:              MyValues { get; private set; }
22:
23:          public Window1()
24:          {
25:              MyValues = new ObservableCollection<string>();
26:              MyValues.Add("array");
27:              MyValues.Add("element");
28:              MyValues.Add("bindings");
29:              //use the ObservableCollection<string> MyValues  as
30:              //the DataContext for the Window
31:              this.DataContext = MyValues;
32:              InitializeComponent();
33:          }
34:
35:          private void Button_Click_0(
36:              object sender, RoutedEventArgs e)
37:          {
38:              MyValues.Clear();
39:              MyValues.Add("bindings");
40:              MyValues.Add("element");
41:              MyValues.Add("array");
42:          }
43:
44:          private void Button_Click_1(
45:              object sender, RoutedEventArgs e)
46:          {
47:              MyValues.Clear();
48:              MyValues.Add("element");
49:              MyValues.Add("bindings");
50:              MyValues.Add("array");
51:          }
52:
53:          private void Button_Click_2(
54:              object sender, RoutedEventArgs e)
55:          {
56:              MyValues.Clear();
57:              MyValues.Add("array");
58:              MyValues.Add("bindings");
59:              MyValues.Add("element");
60:          }
61:      }
62:  }

And here is the XAML code. This is where the individual elements are bound to the MyValues collection. Let's see:

XML
 1:  <Window x:Class="WPF_test.Window1″
 2:      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3:      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4:      Title="Window1″ Height="300″ Width="300″>
 5:
 6:
 7:      <Window.Resources>
 8:          <ContentPresenter x:Key="cont1″ Content="{Binding Path=.[0], Mode=OneWay}"/>
 9:          <ContentPresenter x:Key="cont2″ Content="{Binding Path=.[1], Mode=OneWay}"/>
10:          <ContentPresenter x:Key="cont3″ Content="{Binding Path=.[2], Mode=OneWay}"/>
11:      </Window.Resources>
12:
13:      <StackPanel Orientation="Vertical">
14:          <Button Content="{DynamicResource cont1}" Click="Button_Click_0″/>
15:          <Button Content="{DynamicResource cont2}" Click="Button_Click_1″/>
16:          <Button Content="{DynamicResource cont3}" Click="Button_Click_2″/>
17:      </StackPanel>
18:
19:
20:  </Window>

And real guts of this post is the Content=”{Binding Path=.[0], Mode=OneWay}” part, see how it uses the . notation, which means current Binding, and the [0] indexer.

Neat, huh? And here it is running:

37352/image-thumb20.png

You can see a demo project here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions

 
GeneralBinding with Complex Type property Pin
Sejton212-Jan-11 23:09
Sejton212-Jan-11 23:09 
% Stars Post !

Additional information:

In case, if item of ItemsSource list is not simple type, need use Converter to binding
Something like this:
<code> 
<TextBlock Text="{Binding Path=EachColumnNewLong[0], Converter={StaticResource ResourceKey=ObjectToStringConverter}, diagnostics:PresentationTraceSources.TraceLevel=High}" />
</code>

Where ObjectToStringConverter looks like this:


<code> 
public class ObjectToStringConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            long rv = -2;
            try
            {
                if (value!= null)
                {
                    rv  = ((MyCustomType)value).MyProperty;
                }              
            }
            catch
            {
            }
            return rv.ToString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
  }


public class MyCustomType
{
      public string MyProperty{get;set;}
}

</code>

GeneralBinding to object property in hash table Pin
DTh19789-Jan-10 20:51
DTh19789-Jan-10 20:51 
GeneralRe: Binding to object property in hash table Pin
Sacha Barber9-Jan-10 22:19
Sacha Barber9-Jan-10 22:19 
GeneralAwesome little script Pin
jasonp127-Jan-10 9:14
jasonp127-Jan-10 9:14 
GeneralRe: Awesome little script Pin
Sacha Barber7-Jan-10 23:10
Sacha Barber7-Jan-10 23:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.