Установить правильный контекст в ItemTemplate пользовательского элемента управления

Я использую листбокс элемент для отображения коллекции объектов Participant. У указанного объекта ест свойство NameShort1 которое я использую для отображения элементов в листбоксе:

 <ListBox  Height ="auto" Grid.Row="1" ItemsSource="{Binding Participants}" SelectedItem="{Binding SelectedParticipant}"> 
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding NameShort1}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Затем я решил вынести этот листбокс в отдельный элемент управления UCListBox, чтобы повторно его использовать. После добавления свойств зависимости мой листбокс теперь выглядит следующим образом:

<ListBox ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
         SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"
         >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding MainLabel, RelativeSource={RelativeSource AncestorType=local:UCListBox}}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

CodeBehind:

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

    public object ItemsSource
    {
        get { return (object)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(object), typeof(UCListBox), new PropertyMetadata(null));

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SelectedItem.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(UCListBox), new PropertyMetadata(null));


    public string MainLabel
    {
        get { return (string)GetValue(MainLabelProperty); }
        set { SetValue(MainLabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MainLabel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MainLabelProperty =
        DependencyProperty.Register("MainLabel", typeof(string), typeof(UCListBox), new PropertyMetadata(string.Empty));
}

Теперь я пробую использовать UCListBox в коде:

<local:UCListBox
    ItemsSource="{Binding Participants}"
    SelectedItem="{Binding SelectedParticipant}"
    MainLabel ="{Binding NameShort1}"
/>

Результат: Строки Листбокса "пустые", привязка свойства NameShort1 не происходит. Судя по ошибке контекстом свойства NameShort1 является вся моя модель представления, а не конкретный элемент листбокса. Как я могу установить правильный контекст свойства чтобы шаблон данных отображался корректно?


Ответы (0 шт):