Связывание между Usercontrol со списком и родительским контролем (MVVM) - PullRequest
0 голосов
/ 01 июня 2010

У меня есть UserControl, который содержит список и несколько кнопок.

<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>

И код позади:

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); }
 }

Я использую этот элемент управления в виде, подобном этому:

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

Команда работает нормально, но привязка списка не работает. У меня вопрос - ПОЧЕМУ?

1 Ответ

3 голосов
/ 01 июня 2010

ListBox в вашем UserControl не правильно связывается с LBItems. DataContext из ListBox не является вашим элементом управления, поэтому он пытается связать LBItems непосредственно из вашей ViewModel.

В вашей декларации UserControl добавьте DataContext="{Binding RelativeSource={RelativeSource Self}}". Это должно правильно установить ваш DataContext на UserControl и позволить вам привязку, чтобы правильно найти свойство LBItems.

Редактировать

Ваш комментарий напомнил мне. Вам необходимо установить DataContext вашей Grid в качестве UserControl. Самый простой способ сделать это - присвоить Grid имя, т.е. <Grid x:Name="LayoutRoot">, а затем в конструкторе для вашего UserControl LayoutRoot.DataContext = this;

Если вы устанавливаете DataContext из UserControl, вы нарушаете привязки вашей виртуальной машины, но если вы устанавливаете их в Grid, верхние привязки по-прежнему работают, и все элементы управления внутри UserControl могут правильно связываться с UserControl.

...