WPF: How to pass whole Control as CommandParameter via XAML?

后端 未结 2 469
野趣味
野趣味 2020-12-25 08:34

I\'m using MVVM and custom ICommand objects are provided by ViewModel layer. One ViewModel object at the same time can be attached via DataContext property to many View obje

相关标签:
2条回答
  • 2020-12-25 09:14

    I'm not sure if I'm reading your example correctly, but it seems to violate a bit of the MVVM principle. (My apologies if I read it incorrectly).

    The idea behind MVVM is to decouple the viewmodel from any dependency on a XAML / View entity. You're breaking that by having the CommandParameter dependent on the usercontrol. What I would do is create state properties in the ViewModel and bind the usercontrol validations to those states, then in CanExecute you can test the values of those properties rather than trying to bind to a usercontrol.

    0 讨论(0)
  • 2020-12-25 09:22

    Just use a binding with no Path :

    <Button DataContext="{Binding}" 
            Command="{Binding Path=SwitchCommand}"
            CommandParameter="{Binding RelativeSource=
                                       {RelativeSource
                                        Mode=FindAncestor,
                                        AncestorType={x:Type ListBoxItem}}}"/>
    
    0 讨论(0)
提交回复
热议问题