动态绑定MenuItems

时间:2013-04-21 17:27:35

标签: c# .net wpf xaml

我正在尝试动态绑定MenuItem

public List<string> LastOpenedFiles { get; set; }是我的数据来源。 我尝试运行的命令是public void DoLogFileWork(string e)

<MenuItem Header="_Recent..."
          ItemsSource="{Binding LastOpenedFiles}">
  <MenuItem.ItemContainerStyle>
    <Style TargetType="MenuItem">
      <Setter Property="Header"
              Value="What should be here"></Setter>
      <Setter Property="Command"
              Value="What should be here" />
      <Setter Property="CommandParameter"
              Value="What should be here" />
    </Style>
  </MenuItem.ItemContainerStyle>
</MenuItem>

我想在LastOpenedFiles的每个条目上点击它以使用我点击的条目值转到DoLogFileWork函数。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

<Setter Property="Header" Value="What should be here"></Setter>

没有,您已将上述内容设置为_Recent...

<Setter Property="Command" Value="What should be here"/>
<Setter Property="CommandParameter" Value="What should be here"/>

您使用的是MVVM方法吗?如果是这样,您需要在Window / Control绑定的ViewModel上公开ICommand,请查看this article中提到的RelayCommand(或者在VS2012中是本地的)相信)。

这是你在VM中设置的那种东西:

    private RelayCommand _DoLogFileWorkCommand;
    public RelayCommand DoLogFileWorkCommand {
        get {
            if (null == _DoLogFileWorkCommand) {
                _DoLogFileWorkCommand = new RelayCommand(
                    (param) => true,
                    (param) => { MessageBox.Show(param.ToString()); }
                );
            }
            return _DoLogFileWorkCommand;
        }
    }

然后在你的Xaml中:

<Setter Property="Command" Value="{Binding ElementName=wnLastOpenedFiles, Path=DataContext.DoLogFileWorkCommand}" />
<Setter Property="CommandParameter" Value="{Binding}"/>

所以在这里,您将Command的{​​{1}}绑定为上面声明的MenuItemDoLogFileWorkCommand绑定到List中的字符串MenuItem绑定到。

相关问题