CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2007
    Posts
    858

    Bind StringCollection to a ListBox

    Can anyone give me an example of how to set this up when the StringCollection is a class member? I've been able to get it to work with a StringCollection that's in project settings, but can quite get it right in the case where it's a member of the class.

    Edit: Apparently StringCollection doesn't support two way binding, so I've switch to a ObservableCollection<string>.

    Just to be clear, I need something like this:

    CS
    Code:
    public partial class MyWindow : Window
    {
      private ObservableCollection<string> mystrings;
    
      ...
    }
    XAML
    Code:
    <Window x:Class="MyWindow"
    ...
    
      <ListBox ItemsSource="{Binding ??? what here ???, Mode="TwoWay"}"/>
    </Window>
    Last edited by Speedo; June 25th, 2011 at 09:40 PM.

  2. #2
    Join Date
    Aug 2007
    Posts
    858

    Re: Bind StringCollection to a ListBox

    Apparently members have to be set up as properties before you can bind to them. I feel dumb now.

  3. #3
    Join Date
    Jun 2011
    Posts
    2

    Re: Bind StringCollection to a ListBox

    It should be not just property, it should be DEPENDENCY property.

    In Window1.xaml.cs:

    public static readonly DependencyProperty MyStringsProperty = DependencyProperty.Register("MyStrings", typeof(ObservableCollection<string>), typeof(Window1), new FrameworkPropertyMetadata(null));
    public ObservableCollection<string> MyStrings
    {
    get
    {
    ObservableCollection<string> p = (ObservableCollection<string>)GetValue(MyStringsProperty);
    return p;
    }
    set
    {
    SetValue(MyStringsProperty, value);
    }
    }

    In Window1.XAML:

    <Window ... x:Name="Wnd1" >
    ...
    <ListBox ... ItemsSource="{Binding ElementName=Wnd1, Path=MyStrings, Mode=TwoWay}"/>
    ...
    </Window>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured