1

我正在尝试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使用我单击的条目值运行。

感谢您的帮助。

4

1 回答 1

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 方法吗?如果是这样,您将需要ICommand在 Window/Control 绑定到的 ViewModel 上公开,请查看本文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}"/>

因此,在这里,您将 绑定CommandMenuItem上面DoLogFileWorkCommand声明的,并CommandParameter绑定到 MenuItem 绑定到的 List 中的字符串。

于 2013-04-21T18:40:21.303 回答