开发者

Binding between Usercontrol with listbox and parent control (MVVM)

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">
    <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 Remove开发者_开发知识库Command}"/>

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜