문제

I have the following XAML used to populate a sub-MenuItem listing with RecentDocuments:

<MenuItem Header="_Recent Studies" 
          ItemsSource="{Binding RecentFiles}"
          AlternationCount="{Binding Path=Items.Count, 
                                     Mode=OneWay, 
                                     RelativeSource={RelativeSource Self}}" 
          ItemContainerStyle="{StaticResource RecentMenuItem}"/>

Where in the ViewModel I have the following RecentFiles property

private ObservableCollection<RecentFile> recentFiles = new ObservableCollection<RecentFile>();
public ObservableCollection<RecentFile> RecentFiles
{
    get { return this.recentFiles; }
    set
    {
        if (this.recentFiles == value)
            return;
        this.recentFiles = value;
        OnPropertyChanged("RecentFiles");
    }
}       

Now this works fine and displays my recent menu items like so:

MenuItems

My question is; how can I bind to the click event on my recent files MenuItems? I am amble to use AttachedCommands but I don't see how this can be achieved.

thanks for your time.

도움이 되었습니까?

해결책

If you are using MVVM pattern, you do not need Click event at all.

You should use MenuItem.Command property in order to communicate with your ViewModel.

HOW?

As I can see, you are using the ItemContainerStyle. You can add the following line to that style:

<Style x:Key="RecentMenuItem" TargetType="MenuItem">
    ...
    <Setter Property="Command" Value="{Binding Path=SelectCommand}" />
    ...
</Style>

And in your RecentFile:

 public ICommand SelectCommand { get; private set; }

You can initialize the command inside the constructor of RecentFile class.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top