Question

iv'e created a custom control deriving from ItemsControl .

public class CustsomItemsControl : ItemsControl
{ }

XAML :

  <local:CustsomSelectorControl ItemsSource="{Binding People}"> 
        <local:CustsomSelectorControl.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Name}"/>                  
            </DataTemplate>
        </local:CustsomSelectorControl.ItemTemplate>
    </local:CustsomSelectorControl>     

The Control Template :

<Style TargetType="{x:Type local:CustsomItemsControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustsomItemsControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ItemsPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

in DataContext :

   public MainWindow()
    {
        InitializeComponent();

        People = new ObservableCollection<Person>();
        People.Add(new Person("A"));
        People.Add(new Person("B"));
        People.Add(new Person("C"));
    }

    private ObservableCollection<Person> _people;
    public ObservableCollection<Person> People
    {
        get { return _people; }
        set
        {
            _people = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("People"));
        }
    }

The items are never set , iv'e observed this with snoop ,the ItemsSource property is marked in RED but there are no BindingErrors , when i delve the BindingExpression i get an ArgumentExpression:

 Cannot set Expression. It is marked as 'NonShareable' and has already been used.
Was it helpful?

Solution

Set the DataContext properly:

public MainWindow()
{
    InitializeComponent();
    DataContext = this; //This is what you're missing
    ...
}

Still, you need to have a really strong reason to subclass ItemsControl.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top