将图标添加到WPF中的动态菜单项

问题描述 投票:0回答:1

我试图动态生成MenuItem。我怎么能把它与风格捆绑在一起?

这是代码。

XAML

<Window.Resources>        
    <Image x:Key="Image.Icon" 
     Source="pack://application:,,,/DynamicMenu;component/icon.png"/>        
</Window.Resources>        
<DockPanel>
    <Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}">
        <Menu.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Command" Value="{Binding Command}" />
                <Setter Property="Icon">
                    <Setter.Value>
                        <Image Source="{Binding ImagePath}" Width="12" Height="12" />
                    </Setter.Value>
                </Setter>
            </Style>
        </Menu.ItemContainerStyle>
        <Menu.ItemTemplate>
            <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" 
                                      ItemsSource="{Binding Path=MenuItems}">
                <StackPanel Orientation="Horizontal">                            
                    <TextBlock Text="{Binding Header}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </Menu.ItemTemplate>
    </Menu>
    <Grid>
    </Grid>
</DockPanel>

视图模型

public class MenuItemViewModel
{
    private readonly ICommand _command;

    public MenuItemViewModel()
    {
        _command = new CommandViewModel(Execute);
    }
    public string Header { get; set; }
    public string Param1 { get; set; }
    public string ImagePath { get; set; }
    public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
    public ICommand Command
    {    
        get {return _command; }
    }
    private void Execute()
    {
        MessageBox.Show("Clicked at " + Header + Param1);
    }
}

命令

public class CommandViewModel : ICommand
{
    private readonly Action _action;
    public CommandViewModel(Action action)
    {            
        _action = action;        
    }

    public void Execute(object o)        
    {
        _action();        
    }

    public bool CanExecute(object o)        
    {
        return true;        
    }

    public event EventHandler CanExecuteChanged
    {            
        add { }            
        remove { }        
    }
}

我想为不同的MenuItem添加一个不同的图标。所以我打算将图标文件作为MenuItemViewModel属性传递。需要一种方法将icon属性绑定到MenuItem。谢谢。

wpf xaml menuitem
1个回答
1
投票

我找到了一个解决方案:

<MenuItem Header="{Binding Path=Header}" Command="{Binding PresentationTripLegCommand}">
    <MenuItem.Icon>
        <Image Source="{Binding IconFileName}" Height="16" />
    </MenuItem.Icon>
</MenuItem>
© www.soinside.com 2019 - 2024. All rights reserved.