简体   繁体   中英

In WPF how do you access an object defined in Window.xaml from a nested user control?

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.

SelectedItem=”{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedValue}”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM