WPF MVVM - Command binding inside of an ItemsControl

前端 未结 3 485
抹茶落季
抹茶落季 2021-02-03 12:00

I\'m currently converting a small WPF project to MVVM. I have a List in the ViewModel of the main window that my ItemsControl binds to and uses

3条回答
  •  时光取名叫无心
    2021-02-03 12:50

    Do I bind the ItemsControl.ItemsSource to a collection of a new ViewModel class that represents each item?

    Whether you create a CustomObjectViewModel to host the command or place the command within the same ViewModel that has the list really depends on the function of the action occuring. Is it something that belongs with the CustomObject, or is it something that belongs with your current ViewModel?

    Or is there some kind of binding expression I can use to refer back to the DataContext of the window to have access to bind to the ViewModel (as I type this, it just sounds bad so I'm assuming a big "NO" to this idea)?

    This isn't as bad as it sounds. You don't really need the DataContext of the Window, just the DataContext from before it switched over to the individual items. So if your command was on the same ViewModel that hosts the List of CustomObjects, you could bind to it from within one of the CustomObject's DataTemplate using either of these methods:

    {Binding ElementName=uiCustomObjectsItemsControl, Path=DataContext.MyCommand}
    {Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.MyCommand}
    

    Also, what I want to bind my command to is the LeftMouseButtonUp event of a Grid control. There's no "Command" for a Grid, so I was attempting to use InputBindings.

    For this, I would use something like Attached Command Behaviors which will let you attach a ICommand to any event.

提交回复
热议问题