2013-04-21 93 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