views:

225

answers:

1

I have a UserControl which contains a listbox and few buttons.

<UserControl x:Class="ItemControls.ListBoxControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"&gt;
    <Grid>
        <ListBox:ExtendedListBox SelectionMode="Single" ItemsSource="{Binding LBItems}" Height="184">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <CheckBox Content="{Binding}"/>
                    </DataTemplate>
                </ListBox.ItemTemplate>
        </ListBox>
<Button Command="RemoveCommand"/>
</Grid>
</UserControl>

And the code behind:

public static readonly DependencyProperty RemoveCommandProperty =
 DependencyProperty.Register("RemoveCommand", typeof(ICommand), typeof(ListBoxControl), null);

 public ICommand RemoveCommand
 {
  get { return (ICommand)GetValue(RemoveCommandProperty); }
  set { SetValue(RemoveCommandProperty, value); }
 }

 public static readonly DependencyProperty LBItemsProperty =
 DependencyProperty.Register("LBItems", typeof(IEnumerable), typeof(ListBoxControl), null);

 public IEnumerable LBItems
 {
  get { return (IEnumerable)GetValue(LBItemsProperty); }
  set { SetValue(LBItemsProperty, value); }
 }

I'm using this control in the view like this:

<ItemControls:ListBoxControl Height="240" Width="350" LBItems="{Binding Items, Converter={StaticResource ItemsConverter}, Mode=TwoWay}" RemoveCommand="{Binding RemoveCommand}"/>

The command works fine, though the listbox binding doesn't. My question is - WHY?

A: 

The ListBox in your UserControl isn't correctly binding to LBItems. The DataContext of the ListBox is not your control so it's trying to bind LBItems directly from your ViewModel.

In your UserControl declaration add DataContext="{Binding RelativeSource={RelativeSource Self}}". That should correctly set your DataContext to the UserControl and allow you binding to correctly locate the LBItems property.

Edit

Your comment reminded me. You need to set the DataContext of your Grid to be your UserControl. The simplest way to do this is to name the Grid i.e. <Grid x:Name="LayoutRoot"> and then in the constructor for your UserControl LayoutRoot.DataContext = this;

If you set the DataContext of the UserControl you break the bindings from your VM, but if you set them on the Grid the top bindings still work and all controls inside the UserControl can correctly bind to the UserControl.

Stephan
I've tried this code earlier today (this.DataContext = this in initialization) and just tried this suggestion, but still no luck.
Walkor
I think I know the problem. Edited my answer to show.
Stephan
Awesome! Many thanks, Stephan. You made my day, i spent 10 hours on this.
Walkor