【问题标题】:Set visibility of Context Menu Items in WPF depending on other menu items根据其他菜单项设置 WPF 中上下文菜单项的可见性
【发布时间】:2016-11-21 14:20:54
【问题描述】:

我有一个带有分层数据的树视图控件。它有一个包含四个选项的上下文菜单:展开、全部展开、折叠、全部折叠。我目前正在使用以下类来显示/隐藏上下文菜单项:

Public Class clsTreeContextMenuVisibilityConverter
Implements IValueConverter

Public Function Convert(InValue As Object, InTargetType As Type, InParameter As Object, InCulture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert


    Dim node As TreeNode = Nothing

    If InValue Is Nothing Then
        Return Binding.DoNothing
    End If

    node = DirectCast(InValue, TreeNode)

    If InValue.[GetType]() <> GetType([Boolean]) Then
        If node.HasChildren AndAlso node.ParentNode Is Nothing Then 
            If node.IsExpanded Then
                Return Visibility.Collapsed
            End If              
            Return Visibility.Visible
        End If
    End If

    Return Binding.DoNothing

End Function

Public Function ConvertBack(InValue As Object, InTargetType As Type, InParameter As Object, InCulture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
    Throw New NotImplementedException()
End Function

结束类

XAML:

<Style  x:Key="ExpandMenuItemStyle"
    TargetType="MenuItem">
    <Setter Property="FontWeight" Value="Bold" />
    <Setter Property="Visibility" Value="{Binding Converter={StaticResource VisConverter}}" />
</Style>

 <MenuItem Header="Expand" Style="{StaticResource ExpandMenuItemStyle}" />

VisConverter 是转换器类的 x:Key。我的问题是,如果节点展开,我应该看到 Collapse,反之亦然。此外,如果它是根父级节点,那么我应该看到全部展开。那么我是否必须为所有四种情况编写单独的转换器,还是有一种智能的方法可以做到这一点?

如果需要更多信息,请告诉我。

【问题讨论】:

    标签: wpf contextmenu collapse expand


    【解决方案1】:

    您可能需要两个转换器或两对转换器。一种用于展开状态,一种用于返回节点是父节点还是子节点。如果您只选择两个转换器,则需要一个参数来确定转换器应该返回Visibility.Visible 还是Visibility.Collapsed

    使用四个转换器,您将不需要参数。

    【讨论】:

    • 我并没有完全使用两个转换器,但是您的回答让我想到了将菜单项名称作为 ConverterParameter 传递,然后我可以在一个转换器类中处理所有四种情况。
    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多