5

下面代码的问题是:绑定到SomeClassProp.SubTextProp不起作用(源属性未设置为文本框内容),而绑定到TextProp它。

XAML:

<Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Name="wMain"
        SizeToContent="WidthAndHeight">
    <StackPanel>
        <TextBox Text="{Binding ElementName=wMain, Path=SomeClassProp.SubTextProp}" Width="120" Height="23" />
        <TextBox Text="{Binding ElementName=wMain, Path=TextProp}" Width="120" Height="23" />
    </StackPanel>
</Window>

和代码:

public partial class MainWindow : Window
{
    public SomeClass SomeClassProp { get; set; }
    public string TextProp { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        SomeClassProp = new SomeClass();
    }
}

public class SomeClass
{
    public string SubTextProp { get; set; }
}

我在这里遗漏了一些明显的东西吗?

请注意,我需要此绑定才能从目标(文本框)到源(类属性)。

更新:当我将绑定更改ElementName=wMainRelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}- 两个绑定都有效。所以问题是特定于ElementName绑定属性的。

4

1 回答 1

7

好的,终于,我发现了问题!

添加diag:PresentationTraceSources.TraceLevel=High到绑定 defs 后(顺便说一句,非常有用的东西,在没有正常的 ol' 逐步调试的情况下),我在输出中看到以下内容:

System.Windows.Data 警告:108:BindingExpression (hash=54116930):在级别 0 - 对于 MainWindow.SomeClassProp 找到访问器 RuntimePropertyInfo(SomeClassProp)
System.Windows.Data 警告:104:BindingExpression (hash=54116930):使用访问器 RuntimePropertyInfo(SomeClassProp) 将级别 0 的项目替换为 MainWindow (hash=47283970)
System.Windows.Data 警告:101 : BindingExpression (hash=54116930): GetValue at level 0 from MainWindow (hash=47283970) using RuntimePropertyInfo(SomeClassProp):
System.Windows.Data 警告:106:BindingExpression (hash=54116930):第 1 级的项目为空 - 没有访问器
System.Windows.Data 警告:80:BindingExpression (hash=54116930):TransferValue - 得到原始值 {DependencyProperty.UnsetValue}
System.Windows.Data 警告:88:BindingExpression (hash=54116930):TransferValue - 使用回退/默认值''
System.Windows.Data 警告:89:BindingExpression (hash=54116930):TransferValue - 使用最终值''

问题出在 MainWindow 初始化的顺序上!

因此,在构造绑定的那一刻,我的 0 级属性 ( SomeClassProp) 尚未初始化,这导致绑定完全失败(由于某种原因没有发出正常级别的绑定警告)。

长话短说 -在in构造函数SomeClassProp成功之前移动初始化,绑定也开始使用:InitializeComponent()MainWindowElementName

public MainWindow()
{
    SomeClassProp = new SomeClass();
    InitializeComponent();
}

问题的答案 - 为什么它使用RelativeSource属性起作用 - 在于输出日志的这些行

System.Windows.Data Warning: 66 : BindingExpression (hash=28713467): RelativeSource (FindAncestor) requires tree context
System.Windows.Data Warning: 65 : BindingExpression (hash=28713467): Resolve source deferred

数据上下文初始化RelativeSource需要树上下文,并在构建后推迟到某个时间点Window(那时SomeClassProperty已经初始化)。

于 2013-08-24T14:24:04.297 回答