简体   繁体   中英

Binding to child properties from parent control

I have an user control:

<UserControl x:Class="WpfApplication2.Control1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:WpfApplication2"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <StackPanel Orientation="Horizontal" Name="StackPanelInsideUserControl">
        <Label />
        <TextBox Name="TextBoxInsideUserControl" Text="Initial Text" />
        <Button Content="OK" />
    </StackPanel>
</Grid>

And I'm trying to bind to the Text property of the TextBoxInsideUserControl TextBox from a its parent like in:

<Window x:Class="WpfApplication2.MainWindow"
    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"
    xmlns:local="clr-namespace:WpfApplication2"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <local:Control1 StackPanelInsideUserControl.TextBoxInsideUserControl.Text="{Binding SomeText}" />
</Grid>

How can I achieve that? Does xaml allow us to do that?

As requested, the comment as answer:

No, not really. You should define a dependency property on that UserControl , bind that to the Text of the TextBox . Then you can access the text outside of the UserControl via that dependency property.

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