【问题标题】:Mistake in simple XAML binding简单 XAML 绑定中的错误
【发布时间】:2011-07-27 12:57:55
【问题描述】:

为什么这个绑定不更新?

代码: 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>

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>

【问题讨论】:

    标签: c# .net wpf xaml data-binding


    【解决方案1】:

    由于其保护级别,UserControl 内的 TextBox 是不可访问的,它也是一个字段,您永远不能绑定到这些字段。您需要在 UserControl 后面的代码中将其公开为公共属性。

    public TextBox Txt
    {
        get { return txt; }
    }
    

    编辑:正如 Henk Holterman 指出的那样,您可能不想公开整个 TextBox,因此您可以定义一个 TextBox 内部绑定的依赖属性。

    【讨论】:

    • 是的,这行得通。不明白为什么,它被标记为内部,应该是可见的。
    • 然后公开一个字符串属性,而不是一个文本框。
    • @Poma:在绑定中,所有内容都必须是公共属性,字段不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多