Search code examples
silverlightbindingdatacontextitemscontrol

In an ItemControl binding to property doesent work but binding to DataContext does


when I run this code the Item-object in my CustomControl becomes a System.Windows.Data.Binding containing nothing but null values but the DataContext becomes an MyClass object (which Items is populated with)

<UserControl x:Name="thisControl">

<Grid x:Name="LayoutRoot">
    <ItemsControl ItemsSource="{Binding ElementName=thisControl,Path=Items}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <local:UniformGrid Columns="1"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <local:CustomControl Item="{Binding}" DataContext="{Binding}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>
</UserControl>

My CustomControl class

public partial class CustomControl : UserControl
{
    public CustomControl()
    {
        InitializeComponent();
    }

    public object Item { get; set; }
}

is there something i don't know about ItemsControl? this is written in Silverlight 4.0

Thanks in advance!


Solution

  • There is no need for you to be attempting to assign the custom control DataContext. The ItemsControl will take care of that for you.

    Also your CustomControl code needs to specify the Item property as a DependencyProperty for the binding to work. Binding doesn't work on plain ordinary properties.

    Example:

        public object Item
        {
            get { return GetValue(ItemProperty); }
            set { SetValue(ItemProperty, value); }
        }
    
        public static readonly DependencyProperty ItemProperty =
            DependencyProperty.Register(
                "Item",
                typeof(object),
                typeof(CustomControl),
                new PropertyMetadata(null))
    

    (I assume that RSListBoxStopItem is a typo and you meant to generalise to CustomControl)