私の WPF アプリケーションではMainWindow
、コントロールがあり、GraphControl
XAML マークアップによってウィンドウ内にユーザー コントロールが配置されています。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
}
GraphViewModel.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
}
GraphView.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
View Model クラスに適切に適用されます。
ただし、現時点では、アクセシビリティのために、定義に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
、View Model クラスには適用されません。
私の場合、プログラムで DataTemplate を適用するにはどうすればよいですか?