0

我创建了如下自定义样式

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上课。问题是什么?

4

1 回答 1

0

一个好的方法是在你的 -Class 中实现Style-properties 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您的 Style 以使事情更清晰。

接下来的事情是在你的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. 这应该是全部。

于 2018-09-25T14:47:17.117 回答