Linking between Usercontrol with a List and Parental Controls (MVVM)

I have a UserControl that contains a list and a 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">
    <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 use this control in a view as follows:

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

The command works fine, although list binding does not work. My question is WHY?

0
source share
1 answer

The ListBox in your UserControl is not bound correctly to LBItems. The DataContext ListBox is not your control, so it tries to link LBItems directly to your ViewModel.

In your UserControl ad add DataContext="{Binding RelativeSource={RelativeSource Self}}". This should correctly set the DataContext in the UserControl and allow you to bind the LBItems properties to the correct location.

Edit

. DataContext UserControl. - Grid i.e. <Grid x:Name="LayoutRoot">, UserControl LayoutRoot.DataContext = this;

DataContext UserControl, , Grid, , UserControl UserControl.

+3

All Articles