【问题标题】:How to Write Triggers and Setters for a TreeView through C# rather than XAML如何通过 C# 而不是 XAML 为 TreeView 编写触发器和设置器
【发布时间】:2012-01-23 09:01:53
【问题描述】:

如何将以下基于 XAML 的触发器从 Code behind 而不是 XAML 添加到 TreeView。

<TreeView>
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="Menu Item 1" />
                            <MenuItem Header="Menu Item 2" />
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
        <TreeViewItem Header="Item 1">
            <TreeViewItem Header="Sub-Item 1"/>
        </TreeViewItem>
        <TreeViewItem Header="Item 2"></TreeViewItem>
    </TreeView>

WPF 的默认行为是在 ContextMenu 打开时将 TreeViewItem 更改为灰色,但与 WPF 中的几乎所有其他内容一样,您可以覆盖它:

创建附加属性 ContextMenuOpened 在 TreeViewItem 样式中,将 ContextMenuOpened 绑定到“ContextMenu.IsOpen” 添加当 ContextMenuOpened 和 IsSelected 都为 true 时更改画笔的触发器 这是附加的属性:

public class TreeViewCustomizer : DependencyObject
{
  public static bool GetContextMenuOpened(DependencyObject obj) { return (bool)obj.GetValue(ContextMenuOpenedProperty); }
  public static void SetContextMenuOpened(DependencyObject obj, bool value) { obj.SetValue(ContextMenuOpenedProperty, value); }
  public static readonly DependencyProperty ContextMenuOpenedProperty = DependencyProperty.RegisterAttached("ContextMenuOpened", typeof(bool), typeof(TreeViewCustomizer));
}

这是样式中的二传手:

<Setter Property="my:TreeViewCustomizer.ContextMenuOpened"
        Value="{Binding ContextMenu.IsOpen, RelativeSource={RelativeSource Self}}" />

这里是触发器:

<MultiTrigger>
  <MultiTrigger.Conditions>
    <Condition Property="IsSelected" Value="true"/>
    <Condition Property="my:TreeViewCustomizer.ContextMenuOpened" Value="true"/>
  </MultiTrigger.Conditions>
  <Setter TargetName="Bd"
          Property="Background"
          Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
  <Setter Property="Foreground"
          Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
</MultiTrigger>

我的应用程序中的所有树都是在运行时通过 C# 代码创建的。 我想通过 C# 代码完成上述所有工作,因为我在运行时创建了我的树 通过使用以下代码

TreeView _objTreeView =  new TreeView();

参考问题:WPF TreeViewItem Context Menu Unhighlights Item

【问题讨论】:

    标签: c# .net wpf xaml dependency-properties


    【解决方案1】:

    使用以下语句完成

    SolidColorBrush colorBrush = new SolidColorBrush(Colors.DodgerBlue); myTreeView.Resources.Add(SystemColors.ControlBrushKey, colorBrush);

    :)

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      相关资源
      最近更新 更多