Установить GroupStyle внутри стиля на xaml - PullRequest
1 голос
/ 07 марта 2012

Я пытаюсь установить стиль по умолчанию для ContexMenu, и я хочу установить GroupStyle по умолчанию для ContexMenu внутри стиля.Примерно так:

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

Но компилятор сообщает об ошибке: он не может найти GroupStyle на ItemsControl.

Однако в коде я могу сделать просто:

ContextMenu contextMenu;
contextMenu.GroupStyle.Add(someSavedStyle);

Как мне добиться этого в xaml?

Заранее спасибо!

Ответы [ 3 ]

3 голосов
/ 24 июня 2013

Вы можете использовать присоединенное свойство, чтобы упростить добавление групповых стилей:

<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);
        }
    }
}
0 голосов
/ 16 мая 2012

Я решил это путем создания нового элемента управления, наследуемого от элемента управления ListBox, который добавляет привязываемый DefaultGroupStyle:

    public class MyListBox : ListBox
    {
        public GroupStyle DefaultGroupStyle
        {
            get { return (GroupStyle)GetValue(DefaultGroupStyleProperty); }
            set { SetValue(DefaultGroupStyleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DefaultGroupStyle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DefaultGroupStyleProperty =
            DependencyProperty.Register("DefaultGroupStyle", typeof(GroupStyle), typeof(MyListBox), new UIPropertyMetadata(null, DefaultGroupStyleChanged));

        private static void DefaultGroupStyleChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            ((MyListBox)o).SetDefaultGroupStyle(e.NewValue as GroupStyle);
        }

        private void SetDefaultGroupStyle(GroupStyle defaultStyle)
        {
            if (defaultStyle == null)
            {
                return;
            }

            if (this.GroupStyle.Count == 0)
            {
                this.GroupStyle.Add(defaultStyle);
            }
        }
    }
0 голосов
/ 11 марта 2012

На самом деле, с некоторой дополнительной работой это можно сделать:
Вместо установки шаблона ContexMenu на ItemsPresenter, вы можете установить его для управления, который будет соответствовать вашим данным. В этом случае вы можете установить его на Menu. Просто так:

<Style TargetType="ContextMenu">
     <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ContextMenu">
                        <Border>
                            <Menu ItemsSource="{TemplateBinding ItemsSource}">
                                <Menu.GroupStyle>
                                    <GroupStyle>
                                        <GroupStyle.ContainerStyle>
                                            <Style TargetType="{x:Type GroupItem}">
                                                <Setter Property="Template">
                                                   <Setter.Value>
                                               <ControlTemplate TargetType="{x:Type GroupItem}">
                                                            <StackPanel>
                                                                <Border Background="Black">
                                                                   <ItemsPresenter/>
                                                                </Border>
                                                            </StackPanel>
                                                        </ControlTemplate>
                                                    </Setter.Value>
                                                </Setter>
                                            </Style>
                                        </GroupStyle.ContainerStyle>
                                    </GroupStyle>
                                </Menu.GroupStyle>
                                <Menu.ItemsPanel>
                                    <ItemsPanelTemplate>
                                        <StackPanel></StackPanel>
                                    </ItemsPanelTemplate>
                                </Menu.ItemsPanel>
                            </Menu>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>       
        </Style>

Теперь, хотя GroupStyle только для чтения, мы можем установить его через PropertyElement: -)

Чтобы получить точное представление о MenuItem из ContexMenu, вы можете настроить стиль MenuItem

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...