以 sub-class 作为设置的自定义控件的 WPF 复杂绑定

WPF complex binding for custom control with sub-class as settings

现在我正在尝试实现自定义控件(这当然比我附加的演示解决方案复杂得多),但我未能通过绑定向下传递值。

首先控件的结构:

这样做的目的是将文本从控件(如文本框或其他东西)传递到渲染器,渲染器根据设置的引用进行初始化。

使用控件的XAML写法如下:

<TextBox Text="Initial Text"
        x:Name="TextSource"
        Grid.Row="0" />
<local:CustomControl Grid.Row="1">
    <local:CustomControl.Settings>
        <local:CustomControlSettings Text="{Binding Path=Text, ElementName=TextSource, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
    </local:CustomControl.Settings>
</local:CustomControl>

当我使用相同的 XAML,但为 "Text" 设置一个固定值时,一切都会按预期工作,但一旦我将其更改为绑定,我就不会连初始值都拿不到了

代码正在传递文本:

  1. 将设置传递给渲染器

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        _renderer = new ControlRenderer();
        _renderer.Initialize(_renderArea, Settings);
    }
    
  2. 将设置文本绑定到渲染器内部文本依赖项属性

    SetBinding(TextProperty, new Binding{Path = new PropertyPath(CustomControlSettings.TextProperty), Source = settings});
    

注意:你可以取消注释没有任何影响,所以如果你问我这应该不是问题。

And here´s a link to the demo solution I created.

经过四个小时的痛苦,后来我找到了解决办法。问题是设置对象不是可视化树的一部分,因此依赖属性没有被解析。

因此,为了能够执行此类操作,您需要将设置添加到可视化树中。我通过将它添加到 CustomControl.

内的 canvas 子级来做到这一点