简单的XAML绑定错误

Pom*_*oma 0 .net c# data-binding wpf xaml

为什么这个绑定更新没有?

代码: MainWindow.xaml

<Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication12"
        Height="350" Width="525">
    <StackPanel>
        <local:UserControl1 x:Name="usr" />
        <TextBlock Text="{Binding ElementName=usr, Path=txt.Text}" />
    </StackPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

UserControl1.xaml

<UserControl x:Class="WpfApplication12.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <TextBox Text="qwe" x:Name="txt" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)

H.B*_*.B. 6

UserControl中的TextBox由于其保护级别而无法访问,也是一个字段,您永远无法绑定到那些.您需要在UserControl后面的代码中公开它作为公共属性.

public TextBox Txt
{
    get { return txt; }
}
Run Code Online (Sandbox Code Playgroud)

编辑:作为亨克Holterman指出,你可能不希望暴露整个文本框,所以你可以定义该文本框内部结合,例如一个依赖属性.