gpt4 book ai didi

wpf - 在 xaml 上设置 GroupStyle 内部样式

转载 作者:行者123 更新时间:2023-12-04 05:55:03 26 4
gpt4 key购买 nike

我正在尝试为 ContexMenu 设置默认样式,并且我想在样式内将默认 GroupStyle 设置为 ContexMenu。像这样的东西:

<Setter Property="ItemsControl.GroupStyle">
<Setter.Value>
<GroupStyle>
<...>
</GroupStyle>
</Setter.Value>
</Setter>

但是编译器说错误:它无法在 ItemsControl 上找到 GroupStyle。

但是,在代码中我可以简单地做:
ContextMenu contextMenu;
contextMenu.GroupStyle.Add(someSavedStyle);

我怎样才能在 xaml 中实现这一点?

提前致谢!

最佳答案

您可以使用附加属性来简化添加组样式:

<Style TargetType="MenuItem">
<Setter Property="b:GroupStyleEx.Append">
<Setter.Value>
<GroupStyle .. />
</Setter.Value>
</Setter>

<!-- you can add as many as you like... -->
<Setter Property="b:GroupStyleEx.Append">
<Setter.Value>
<!-- second group style -->
<GroupStyle .. />
</Setter.Value>
</Setter>
</Style>

这是附加属性的代码:

using System;
using System.Windows;
using System.Windows.Controls;

namespace Util
{
public static class GroupStyleEx
{
public static readonly DependencyProperty AppendProperty
= DependencyProperty.RegisterAttached("Append", typeof (GroupStyle), typeof (GroupStyleEx),
new PropertyMetadata(AppendChanged));

public static GroupStyle GetAppend(DependencyObject obj)
{
return (GroupStyle) obj.GetValue(AppendProperty);
}

public static void SetAppend(DependencyObject obj, GroupStyle style)
{
obj.SetValue(AppendProperty, style);
}

private static void AppendChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var itemsControl = d as ItemsControl;
if (itemsControl == null)
throw new InvalidOperationException("Can only add GroupStyle to ItemsControl");

var @new = e.NewValue as GroupStyle;
if (@new != null)
itemsControl.GroupStyle.Add(@new);
}
}
}

关于wpf - 在 xaml 上设置 GroupStyle 内部样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9598859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com