2013-04-21 95 views
1

我正试图动态绑定MenuItem动态绑定MenuItems

我有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
<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方法上面?如果是这样,你需要在WindowModel上暴露的ICommand,Window/Control绑定到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}"/> 

所以在这里,你绑定MenuItemCommand到是上面声明的DoLogFileWorkCommand,并且CommandParameter正被绑定到MenuItem绑定到的List中的字符串。

+0

感谢您的帮助,您真的很有帮助。 – 2013-04-21 19:22:26