代码之家  ›  专栏  ›  技术社区  ›  Imad

在WPF中添加自定义样式

  •  0
  • Imad  · 技术社区  · 8 年前

    public class MenuStyle: StyleSelector
    {
        public override Style SelectStyle(object item, DependencyObject container)
        {
            // my code
        }
    }
    

    xaml 文件如下。

    我使用它如下。

    xmlns:style="clr-namespace:MedicalStore.Styles"
    

    已将资源添加为

        <UserControl.Resources>
            <style:MenuStyle x:Key="MenuStyle"></style:MenuStyle> 
            <Style TargetType="MenuItem" x:Key="SelectedMenuItem">
                <Setter Property="Background" Value="White"></Setter>
            </Style>
        </UserControl.Resources>
    

    使用方法如下

    <Menu DockPanel.Dock="Top" FontSize="22" Background="Green" HorizontalAlignment="Right" x:Name="MainMenu"
                  ItemsSource="{Binding Path=MenuItems}" DisplayMemberPath="Text" 
                  ItemContainerStyleSelector="{Binding MenuStyle}">
            </Menu>
    

    但当我运行我的应用程序时,调试器永远不会运行 MenuStyle 班级。问题是什么?

    1 回复  |  直到 8 年前
        1
  •  0
  •   c0nn1    8 年前

    一个好的方法是实施 Style MenuStyle -班级。

    public class MenuStyle : StyleSelector
    {
        // Declare all the style you're going to need right here
        public Style StyleMenuItem { get; set; }
    
        public override Style SelectStyle(object item, DependencyObject container)
        {
            // here you can check which type item is and return the corresponding style
            if(item != null && typeof(item) == typeof(YourType))
            {
                 return StyleMenuItem;
            }
        }
    }
    

    XAML

    <UserControl.Resources>
        <Style TargetType="MenuItem" x:Key="SelectedMenuItemStyle">
            <Setter Property="Background" Value="White"></Setter>
        </Style>
        <style:MenuStyle x:Key="MenuStyle" StyleMenuItem="{StaticResource SelectedMenuItemStyle}"/>
    </UserControl.Resources>
    

    请注意,我更改了 x:Key 以使事情更清楚。

    下一件事是在你的 Menu :

    <Menu DockPanel.Dock="Top" FontSize="22" Background="Green" HorizontalAlignment="Right" x:Name="MainMenu"
                  ItemsSource="{Binding Path=MenuItems}" DisplayMemberPath="Text" 
                  ItemContainerStyleSelector="{StaticResource MenuStyle}">
    </Menu>
    

    StaticResource Binding . 就这些了。

    推荐文章