0

Lets have a class:

public partial class MyControl: UserControl{
    private ObservableCollection<string> names = 
            new ObservableCollection<string>();
    ...
}

and then in XAML for the same UserControl that is in XAML for class MyControl:

<UserControl x:Class="MyProject.MyControl" xmlns="..." xmlns:x="...">
    <ItemsControl ItemsSource="{Binding ???????}" />
</UserControl>

Is it possible to replace ??????? by something that will bind ItemsSource to the names field in code behind? What is the right way to do it if there is a way ? If there is no way does names have to be dependency property instead of just a field ?

Rasto
  • 17,204
  • 47
  • 154
  • 245

1 Answers1

3

You just need to make a public getter property for names

public IEnumerable<string> Names
{
     get{return names;}
}

It doesn't need to be a dependency property.

And then your xaml can be

<ItemsControl ItemsSource="{Binding Names}" />

Edit: Just re-read your title. If you want to keep names private, you'd have to do the binding int the code behind.

        Binding b = new Binding();
        b.Source = names;
        itemsControl.SetBinding(ItemsControl.ItemsSourceProperty, b);
wangburger
  • 1,073
  • 1
  • 18
  • 28
  • So that is the right way to do it ? But then I have to expose the `names` as it in the fact becomes public - now everybody can add something to `names`. – Rasto May 10 '11 at 17:14
  • 1
    You can either do the code behind or expose the names collection as IEnumerable since that is readonly. – wangburger May 10 '11 at 17:16
  • Or you can just assign `names` directly to the ItemsSource of the ItemsControl, without a binding... – Thomas Levesque May 10 '11 at 17:21
  • If I expose it as `IEnumerable` (using property with get accessors only) and some new `string` is added to `names` will the change be reflected in GUI ? I'm using `ObservableCollection` because I want that behavior... – Rasto May 10 '11 at 17:30
  • 1
    Yes because although it is exposed as an IEnumerable, it's still an ObservableCollection and will notify the UI. And you can only add names from inside the class since that is the only place where the observable collection of names is in scope. – wangburger May 10 '11 at 17:36
  • @wangburger: Great, great, great! WPF is a wonderful technology and you are a wonderful person in my wonderful life :). This is solved. My usual note: it will not be accepted any time soon, though, I want to to give others a chance to vote up your answer or provide better answer them selfs. – Rasto May 10 '11 at 17:45