【问题标题】:Binding cannot find source when trying to access the datacontext of a custom listview contextmenu尝试访问自定义列表视图上下文菜单的数据上下文时绑定找不到源
【发布时间】:2021-03-08 00:47:52
【问题描述】:

我遇到了与ContextMenu for ListViewItem only 非常相似的问题,但该解决方案似乎不适用于我的情况。

<GroupBox Header="PlayOffs" Grid.Row="2" Grid.Column="0">
    <StackPanel Orientation="Vertical" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <ScrollViewer VerticalScrollBarVisibility="Auto">
            <ListView Grid.Column="0" ItemsSource="{Binding PlayoffSeries}" ItemTemplate="{StaticResource SeriesTemplate}">
                <ListView.Resources>
                   <ContextMenu x:Key="cm">
                       <MenuItem Header="SetLive" Click="SetSeriesLive"/>
                       <MenuItem Header="Start" IsEnabled="{Binding Path=DataContext.CanStart, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}" Click="StartSeries"/>
                   </ContextMenu>
                </ListView.Resources>
                <ListView.ItemContainerStyle>
                    <Style TargetType="{x:Type ListViewItem}">
                        <Setter Property="HorizontalAlignment" Value="Stretch"/>
                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                        <Setter Property="ContextMenu" Value="{StaticResource cm}"/>
                        <EventSetter Event="MouseDoubleClick" Handler="HandleDoubleClick" />
                    </Style>
                </ListView.ItemContainerStyle>
            </ListView>
        </ScrollViewer>
    </StackPanel>
</GroupBox>

MenuItem StartIsEnabled 绑定出现错误Cannot find source:RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ListView',AncestorLevel='1'

点击命令就像一个魅力,基本上我想要做的是将菜单项的 IsEnabled 属性绑定到 listviewItem 提供的基础数据上下文的CanStart 属性。

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    我是个笨蛋。我刚刚尝试使用AncestorType=ContextMenu,它似乎就像一个魅力。仍然不完全确定为什么第一个解决方案适用于另一个问题。我想它与绑定到列表视图的数据模型有关。

    【讨论】:

    • ContextMenu 不是列表视图的可视化树的一部分。这就是为什么在 ContextMenu 中使用 RelativeSource 找不到 ListView 的原因。 ContextMenu 通常与所属控件共享相同的 DataContext。这就是您的解决方案有效的原因。
    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2017-03-28
    • 2013-09-23
    相关资源
    最近更新 更多