【发布时间】:2018-05-21 10:24:50
【问题描述】:
在我的 WPF 应用程序中,我有一个 MainWindow.xaml,其中嵌入了许多用户控件。我对主窗口和用户控件都有单独的视图模型。在主窗口 ViewModel 中,我创建了一个子 ViewModel 的实例并将其设置为子的数据上下文。
父虚拟机 ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);
MainWindow.xaml
但是这种方法不起作用,因为我没有在子视图模型的父视图模型中设置值,反之亦然。
相反,如果我将 Child 模型对象设置为双向工作的父级的数据上下文。
我需要一些解决方案,以便我可以在用户控件中使用 MVVM,同时确保数据从父级传递到子级,反之亦然。 在用户控件中,我将有一些按钮,我想通过 ICommand 在子 Viewmodel 中处理其操作。 添加代码 sn-ps 以供参考 MainWindow.xaml
<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
<local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>
MainWindowVM.cs
ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);
ProfileIdentitySettings.xaml
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">
【问题讨论】:
-
你能展示你的代码吗?
-
我已经添加了代码sn-p。这目前不起作用。
标签: wpf mvvm user-controls