Yoo Matsuo
Yoo Matsuo

Reputation: 2363

How can I bind a parent control's TextBox from inside a user control

I have a user control which tries to bind a parent's control textbox,

TextBlockControl.xaml

<UserControl x:Class="wpf_sandbox.TextBlockControl"
             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" 
             mc:Ignorable="d" >
    <Grid>
        <TextBlock Text="{Binding Text, ElementName=editor}"></TextBlock>
    </Grid>
</UserControl>

MainWindow.xaml

<Window x:Class="wpf_sandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpfSandbox="clr-   namespace:wpf_sandbox"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox x:Name="editor"></TextBox>
        <wpfSandbox:TextBlockControl></wpfSandbox:TextBlockControl>       
    </StackPanel>
</Window>

This doesn't work at all. I tried several ways such as using relative source and source, but none worked either.

Upvotes: 0

Views: 621

Answers (1)

stukselbax
stukselbax

Reputation: 5935

You can declare the DataContext property of the <TextBlockControl /> as the Text property of the "editor" <TextBox />:

<wpfSandbox:TextBlockControl DataContext="{Binding Text, ElementName=editor}" />

and inside your control:

<Grid>
    <TextBlock Text="{Binding}" />
</Grid>

Upvotes: 1

Related Questions