WPF 无法为动态创建的用户控件设置数据上下文

问题描述

这是我正在做的总结:

  1. 创建了一个子模型,并使用子模型的句柄触发了一个事件。
  2. 容器 viewmodel 接收事件,并创建一个包含子模型的句柄的子视图模型。
  3. 在应用程序资源中使用 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 是一个用户控件

如您所见,我正在动态创建多个子模型实例以及相应的子视图模型和子视图,目的是将它们显示在预定位置。在程序执行期间,我也需要删除/删除它们。 SubView需要显示SubModel中多个元素的值。

非常感谢这里的任何帮助。如果我对这一切都做错了,也请随时纠正。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...