首页 > 解决方案 > 为什么 FindAncestor 在 DataTemplate 中的 {Binding} 元素内调用时找不到根 UserControl?

问题描述

首先,对不起标题。如果您有建议,很高兴将其更改为更好的东西。

我是 wpf 的新手,无法解决这个问题。我的 UserControl 数据上下文中有一个属性 List<> Serieslist。此列表中的项目是livecharts SeriesCollection 图表(我认为这个问题与我对 wpf 的无能有关,而不是与 livecharts 有关)。我可以从 StackPanel 找到 UserControl 祖先,但是当在 lvc:CartesianChart 中使用 Series="{Binding}" 我不能。

我的 XAML:

<Grid Grid.Column="1">
            <StackPanel >
                <ItemsControl ItemsSource="{Binding Serieslist}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>

                                <!--These Bindings work as intended-->
                                <TextBlock Text="{Binding Path=DataContext.From, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
                                <TextBlock Text="{Binding Path=DataContext.To, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>


                                <lvc:CartesianChart Height="100" Series="{Binding}" Zoom="X" Grid.Column="0" DisableAnimations="True" DataTooltip="{x:Null}">
                                    <lvc:CartesianChart.AxisX>

                                        <!--These Bindings don't-->
                                        <lvc:Axis LabelFormatter="{Binding Path=DataContext.Formatter, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
                                                  MinValue = "{Binding Path=DataContext.From, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" 
                                                  MaxValue = "{Binding Path=DataContext.To, Mode=TwoWay, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                                                  RangeChangedCommand="{Binding Path=DataContext.Axis_OnRangeChangedCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
                                    </lvc:CartesianChart.AxisX>
                                    <lvc:CartesianChart.AxisY>
                                        <lvc:Axis Foreground="DodgerBlue" MinValue="0"/>
                                        <lvc:Axis Foreground="IndianRed" Position="RightTop" MinValue="0" MaxValue="10"/>
                                    </lvc:CartesianChart.AxisY>
                                </lvc:CartesianChart>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </Grid>

我了解进入 CartesianChart 时 {Binding} 范围的变化,但仍然为什么这种使用 RelativeSource 的方式不能找到正确的绑定源?

这些实时图表轴元素也可以在我的实时视觉树中找到。[Bars] 是 UserControl,不存在其他 UserControl视觉树

对于这样简单的(?)问题,命名祖先元素并使用名称查找数据上下文似乎很麻烦。此外,我可能需要重用这些用户控件,并且我想避免使用 name=usercontrol1 name=usercontrol2 name=usercontrol3 等访问父控件的方式。

谢谢您的帮助!

标签: c#wpf

解决方案


推荐阅读