如何从用户控件内部绑定父控件的TextBox

时间:2013-06-07 02:46:03

标签: wpf

我有一个用户控件试图绑定父控件的文本框

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>

这根本不起作用。我尝试了几种方法,比如使用相对源和源,但都没有用。

1 个答案:

答案 0 :(得分:1)

您可以将&lt; TextBlockControl /&gt; DataContext 属性声明为“编辑器”文本属性&lt; TextBox /&gt;

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

并在你的控制范围内:

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