views:

256

answers:

1

I have a situation where I need to access an object that has been defined in one user control from within a user control nested 2 levels deep. Take the following for example:

public class MyClass
{
    public MyClass()
    {
        MyData = new MyDataProvider();
    }

    public MyDataProvider MyData;
    public string SelectedValue;
}

public class MyDataProvider
{
    public MyDataProvider()
    {
        MyList = new List<string>() { "Test1", "Test2", "Test3" };
    }
    public List<string> MyList;
}

Window.xaml

<Window.DataContext>
    <my:MyClass></my:MyClass>
</Window.DataContext>
<Grid>
    <my:UC1></my:UC1>
</Grid>

UC1.xaml

<Grid Height="Auto" Width="316">
    <my:UC2 Margin="0,0,41,52" DataContext="{Binding Path=MyData}"/>
    <TextBox Text="{Binding SelectedValue}" Margin="22,73,119,113" />
</Grid>

UC2.xaml

 <Grid>
    <StackPanel>
        <Label Content="My List"/>
        <ComboBox Name="comboBox1" ItemsSource="{Binding Path=MyList}" 
                                   SelectedItem="{Binding Path=SelectedValue}"/>
    </StackPanel>
</Grid>

Please ignore the missing Property changed events etc as it's just for example purposes

The above basically shows you my setup. 2 nested user controls where the bottom level one, UC2, tries to set the selected combobox item to the SelectedValue property of the object defined in the Window xaml (MyClass). Problem is that the way I have specified the SelectedItem binding doesn't work. I need to tell it to look up the tree to the Window. This is what I don't know how to do.

Please help.

Thanks alot.

+2  A: 
SelectedItem=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedValue}”
kek444
Great this works well, however is it the only way? It seems a bit of a hack as what if I want to find an element that is a parent of an element of the same type. i.e. <DockPanel x:Name="TheOneIWant"> <DockPanel>
HAdes
For that case you have AncestorLevel, e.g. SelectedItem=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, AncestorLevel=2, Path=DataContext.SelectedValue}”
kek444