无法更改 materialdesigninxaml 的重音

Cannot change accent on materialdesigninxaml

我正在尝试将 MaterialDesign 元素添加到 MenuItem,实际上我已经做到了 部分地,这是我到目前为止所做的:

菜单创建:

 <Menu Grid.Row="0" HorizontalAlignment="Left" VerticalAlignment="Stretch">
            <MenuItem Header="Stile" Width="100" 
                      ItemContainerStyle="{StaticResource AccentColorMenuItemStyle}"
                      ItemsSource="{Binding SettingsController.Swatches, Mode=OneWay}" />
 </Menu>

容器定义:

 <Ellipse x:Key="AccentMenuIcon"
                 Width="16"
                 Height="16"
                 x:Shared="False"
                 Fill="{Binding AccentExemplarHue.Color, Converter={StaticResource ColorToBrushConverter}, Mode=OneWay}" />

    <Style x:Key="AccentColorMenuItemStyle"
           BasedOn="{StaticResource MetroMenuItem}" TargetType="{x:Type MenuItem}">
        <Setter Property="Command" Value="{Binding DataContext.ApplyAccentCommand, 
            RelativeSource={RelativeSource AncestorType=Window}}" />
        <Setter Property="Header" Value="{Binding Name, Mode=OneWay}" />
        <Setter Property="Icon" Value="{StaticResource AccentMenuIcon}" />
    </Style>

我定义了一个颜色转换器来显示为椭圆颜色:

public class ColorToBrushConverter : IValueConverter 
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new SolidColorBrush((Color)value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        SolidColorBrush c = (SolidColorBrush)value;
        System.Drawing.Color col = System.Drawing.Color.FromArgb(c.Color.A, c.Color.R, c.Color.G, c.Color.B);
        return col;
    }
}

然后在我的视图模型中我以这种方式实现:

    private static void ApplyBase(bool isDark)
    {
        new PaletteHelper().SetLightDark(isDark);
    }

    public IEnumerable<Swatch> Swatches { get; }

    public ICommand ApplyPrimaryCommand { get; } = new SimpleCommand(o => ApplyPrimary((Swatch)o));

    private static void ApplyPrimary(Swatch swatch)
    {
        new PaletteHelper().ReplacePrimaryColor(swatch);
    }

    public ICommand ApplyAccentCommand { get; } = new SimpleCommand(o => ApplyAccent((Swatch)o));

    private static void ApplyAccent(Swatch swatch)
    {
        new PaletteHelper().ReplaceAccentColor(swatch);
    }

使用上面的代码,我在 menuItem 中显示了所有重音符号,但是我遇到了一个问题,当

我单击 menuItem 颜色,然后调用命令 "ApplyAccentCommand" 我得到一个空异常 这里:

private static void ApplyAccent(Swatch swatch)
{
    new PaletteHelper().ReplaceAccentColor(swatch);
}

特别是在样本对象(这是重音)上我做错了什么?谢谢。

我怀疑您实际上遇到了 ArgumentNullException。自ReplaceAccentColor checks the incoming parameter for null。如果您在该行设置断点,我怀疑样本为空。

我看到您正在设置命令,但没有设置命令的参数,这意味着将使用默认值 null。

只需在您的菜单项样式中再添加一种 setter 即可解决此问题。

<Setter Property="CommandParameter" Value="{Binding}" />