코드의 리소스 사전에 DataTemplate (XAML이 아닌) 추가?
-
21-09-2019 - |
문제
앱의 리소스 사전에 데이터 emplate을 추가하는 방법을 알아 내려고 노력하고 있습니다. DataTemPlate이 XAML (URI를 통해)에있을 때 그렇게하는 방법에 익숙하지만 DataTemPlate이 코드로 정의 될 때 수행하는 방법에 대해 친절합니다.
내가 가지고 있지 않은 것은
//Create DataTemplate
DataTemplate template = new DataTemplate(typeof(CoordinateViewModel));
FrameworkElementFactory ViewStack = new FrameworkElementFactory(typeof(CoordinateView));
ViewStack.Name = "myViewStack";
template.VisualTree = ViewStack;
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.BeginInit();
dictionary.Add(template, template);
dictionary.EndInit();
App.Current.Resources.MergedDictionaries.Add(dictionary);
편집 : 최선을 다해 DataTemplate은 오류를 던지지 않더라도 앱의 리소스 사전으로 만들지 않습니다. 뷰 모델이 나중에 XAML에서 호출되면,이를 표시하기에 적절한 데이터 템플릿이없는 것처럼 작용합니다. 예를 들어,
<StackPanel>
<ContentPresenter Content="{Binding ViewModel}" />
</StackPanel>
텍스트 "ShellPrototype.viewModels.CoordinateViewModel"이 표시된 텍스트와 함께 빈 창을 표시합니다. 예를 들어보기에 표시 할 템플릿이 없습니다.
해결책
이 작업을 올바르게 만들기 위해 여기서 핵심은 사용하는 것입니다. DataTemPlateKey:
ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Add(new DataTemplateKey(typeof(CoordinateViewModel)), template);
이렇게하면 지정된대로 작동해야합니다. 그러나, 그 FrameworkElementFactory 문서에 따르면, "프로그래밍 방식으로 템플릿을 만들 수있는 감가 상각 된 방법"이므로 XAML을 직접 구문 분석 할 수 있습니다.
제휴하지 않습니다 StackOverflow