Viewmodel commandbinding
Iam using MVVM model and I have three usercontrols in a WPF Main window and each usercontrol has datacontext set to different viewmodels in the xaml. The main window is also attached to a different viewmodel in the datacontext. Mainwindow has three buttons and should be bound via command binding, How can we bind the main window buttons to corresponding usercontrol view model Icommand via xaml?
It's difficult to tell if this is a good solution because there are a lot of missing details about your application architecture.
Based on the premise "I have a window that contains 3 user controls and I want buttons on the window to activate commands on the viewmodels of the controls", one solution could be:
<Window>
<UserControl Name="Control1" />
<UserControl Name="Control2" />
<UserControl Name="Control3" />
<Button Command="{Binding ElementName="Control1", Path="DataContext.Cmd"}" />
<Button Command="{Binding ElementName="Control2", Path="DataContext.Cmd"}" />
<Button Command="{Binding ElementName="Control3", Path="DataContext.Cmd"}" />
</Window>
This is a bit subjective, but in my opinion viewmodels should not be serving more then one view.
The MainWindow's viewmodel should be totally independent from the UserControl's models. I would suggest using a publish/subscriber pattern for sending "events" through your application that handle widely used functionality (see for example Event Aggregator).
If you can't access the ViewModels via a direct binding from DataContext of the MainWindow (ie if the three ViewModels aren't in the MainWindow's ViewModel), you can just do this :
<Button
Name="Button1"
DataContext="{Binding DataContext, ElementName=UserControl1}"
/>
This should work if I understood well what you're asking.
链接地址: http://www.djcxy.com/p/56146.html上一篇: 打开儿童窗口标准
下一篇: Viewmodel命令绑定