如何解决WPF 无法为动态创建的用户控件设置数据上下文
这是我正在做的总结:
- 创建了一个子模型,并使用子模型的句柄触发了一个事件。
- 容器 viewmodel 接收事件,并创建一个包含子模型的句柄的子视图模型。
- 在应用程序资源中使用 DataTemplate,一个子视图(用户控件)被实例化并放置在树中(现有网格位置中的 GroupBox)。
我相信上述方法遵循 MVVM 模式(如果我错了,请纠正我)。
我已经能够完成大部分工作,即视图出现在预期位置,除了我无法将视图的 DataContext 设置为特定的 viewmodel,以便它可以绑定到另一个要显示的 viewmodel 的属性。以下是修改后的代码片段
类 ContainerModel
public bool AddSubModel(SubModel model)
....
mySubModel = model;
ModelAddRemoveEventArgs ePlateAdded = new ModelAddRemoveEventArgs ();
eModelAdded.ModelAdd = true;
eModelAdded.AddedModel = model;
this.PlateAddRemove?.Invoke(this,ePlateAdded);
类 Containerviewmodel
...
public Subviewmodel PlacedVM
{
get { return this.placedVM; }
private set { SetProperty(ref this.placedVM,value); }
}
....
private void OnPlateAddRemoveUpdate(object sender,PlateAddRemoveEventArgs e)
{
// if a plate was added,create a view and place it on the handler
if (e.PlateAdd)
{
Subviewmodel subVM = new Subviewmodel(e.AddedModel);
PlacedVM= subVM;
}
}
MainWindow.xmal.cs
....
private void Window_loaded(object sender,RoutedEventArgs e)
{
....
ObservableCollection<Containerviewmodel> ContainerVMList = mainWindowVM.ContainderviewmodelList;
....
for(all container VMs)
{
//Create a GroupBox and add it to individual locations SubViewGrid (name: subGrid)
Binding placedVMBinding = new Binding();
placedVMBinding.source = ContainerVMList[containerPosNumber - 1];
placedVMBinding.Path = new PropertyPath("PlacedVM");
BindingOperations.SetBinding(created GroupBox,GroupBox.contentproperty,placedVMBinding);
....
...
}
MainWindow.xaml
.....
<Grid Grid.Row="0">
<GroupBox Grid.Row="0" Header="Platen" Margin="10,10,10"
FontSize="14" FontWeight="Bold" BorderThickness="4">
<Grid x:Name="subGrid" Width="Auto" Height="Auto" />
</GroupBox>
</Grid>
....
App.xaml
<Application.Resources>
<DataTemplate DataType="{x:Type local:Subviewmodel}">
<local:SubView/>
</DataTemplate>
<Style targettype="{x:Type Rectangle}" />
</Application.Resources>
如您所见,我正在动态创建多个子模型实例以及相应的子视图模型和子视图,目的是将它们显示在预定位置。在程序执行期间,我也需要删除/删除它们。 SubView需要显示SubModel中多个元素的值。
非常感谢这里的任何帮助。如果我对这一切都做错了,也请随时纠正。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。