bugfixr
bugfixr

Reputation: 8077

Bind DataTemplate to 'outside' property

I've got a TabControl which builds a list of TabItems from it's ItemsSource. Like so:

<TabControl ItemsSource="{Binding Path =.}">
    <TabControl.ItemContainerStyle>
            <Style TargetType="TabItem" BasedOn="{StaticResource BlueTabItem}" >
                <Setter Property="Header" Value="{Binding Path=dataName}"/>
            </Style>
    </TabControl.ItemContainerStyle>
    ...
</TableControl>

As part of the DataTemplate, I need to bind to a List found in my XAML Window where the TabControl resides:

public partical class SomeWindow : Window {
     public List<string> aList {
         get { return new List<string>(); }
     }
}

How can I reference and bind to the aList from within my TabControl's DataTemplate?

Upvotes: 3

Views: 3374

Answers (2)

Yazan Al-Alul
Yazan Al-Alul

Reputation: 482

If you set the RelativeSource of the binding to an Element whose Data Context gives it access to the aList property, then you can set the Binding's Path to aList. So it would look something like this (assuming your window's DataContext gives it access to aList):

ItemsSource={Binding Path=aList, RelativeSource={RelativeSource AncestorType={x:Type Window}}

Upvotes: 4

brunnerh
brunnerh

Reputation: 184376

Use a RelativeSource binding with an AncestorType targeting the window.

Upvotes: 3

Related Questions