如何以编程方式将数据模板应用于视图模型类



在我的 WPF 应用程序中,我有MainWindow控件,并且GraphControl用户控件通过 XAML 标记放置在 Window 中。 GraphControl分配了GraphControlViewModel,它包含附件GraphView控件(派生自Control类)。该类型的实现的大纲(简化)如下:

GraphControl.xaml

<UserControl
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:designer="clr-namespace:Designer"
  xmlns:GraphUI="clr-namespace:GraphUI;assembly=GraphUI"
  xmlns:GraphModel="clr-namespace:GraphModel;assembly=GraphModel">
  /* simplified document content */
  <UserControl.Resources>
    <ResourceDictionary>
      <DataTemplate DataType="{x:Type GraphModel:NodeViewModel}">
          /* data template definition here*/
      </DataTemplate>
    </ResourceDictionary>
  </UserControl.Resources>
  <UserControl.DataContext>
    <designer:GraphControlViewModel />
  </UserControl.DataContext>
  <DockPanel>
    <GraphUI:GraphView NodesSource="{Binding Graph.Nodes}" />
  </DockPanel>
</UserControl>

GraphControlViewModel.cs:

public class GraphControlViewModel : AbstractModelBase
{
    private GraphViewModel graph;
    public GraphViewModel Graph
    {
        get
        {
            return this.graph;
        }
        set
        {
            this.graph = value;
            this.OnPropertyChanged("Graph");
        }
    }
    // implementation here
}

图形视图模型.cs:

public sealed class GraphViewModel
{
    private ImpObservableCollection<NodeViewModel> nodes;
    public ImpObservableCollection<NodeViewModel> Nodes
    {
        get
        {
            return this.nodes ?? ( this.nodes = new ImpObservableCollection<NodeViewModel>() );
        }
    }
    // implementation here
}

NodeViewModel.cs:

public sealed class NodeViewModel : AbstractModelBase
{
   // implementation here
}

图形视图.cs:

public partial class GraphView : Control
{
    // implementation of display details here
    public IEnumerable NodesSource
    {
        get
        {
            return (IEnumerable)this.GetValue(NodesSourceProperty);
        }
        set
        {
            this.SetValue(NodesSourceProperty, value);
        }
    }
}

应用程序的工作方式和外观与它被发明时一样,DataTemplate正确地应用于视图模型类。

但是,目前需要将x:key属性添加到DataTemplate定义中,以实现可访问性目的:

<DataTemplate x:Key="NodeViewModelKey" DataType="{x:Type GraphModel:NodeViewModel}">
    /* data template definition here*/
</DataTemplate>

在这里,我的问题出现了。如 MSDN 上的数据模板化概述文档中所述:

If you assign this DataTemplate an x:Key value, you are overriding the implicit x:Key and the DataTemplate would not be applied automatically.

实际上,在我添加x:Key属性后,DataTemplate不会应用于我的视图模型类。

如何在我的情况下以编程方式应用数据模板?

如果你像这样命名你的GraphView

<GraphUI:GraphView x:Name="myGraph" NodesSource="{Binding Graph.Nodes}" />

在用户控件的代码隐藏中,您可以执行以下操作:

      myGraph.Resources.Add(
      new DataTemplateKey(typeof(NodeViewModel)), 
      Resources["NodeViewModelKey"]);

我会尝试在GraphView中添加一个DataTemplate依赖属性,然后尝试使用它,如下所示:

<GraphUI:GraphView NodesSource="{Binding Graph.Nodes}" 
                   DataTemplate={StaticResource NodeViewModelKey}/>

最新更新