目前我正在使用DataTemplateSelector在我的UserControl.Resources中查找DataTemplates,但我想将它们移动到ResourceDictionary中。如何从DataTemplateSelector中查找ResourceDictionary?
这是我当前的DataTemplateSelector:
public class SettingsDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Setting)
{
Setting registeritem = item as Setting;
if (registeritem.EditValueVar.EditType == EditType.Textfield)
return element.FindResource("TextboxDataTemplate") as DataTemplate;
else if (registeritem.EditValueVar.EditType == EditType.DropDown)
return element.FindResource("ComboDataTemplate") as DataTemplate;
else if (registeritem.EditValueVar.EditType == EditType.Slider)
return element.FindResource("SliderDataTemplate") as DataTemplate;
else
throw new ArgumentOutOfRangeException(registeritem.EditValueVar.EditType.ToString());
}
return null;
}
}
答案 0 :(得分:2)
您可以向ResourceDictionary
班级添加DataTemplateSelector
媒体资源:
public class SettingsDataTemplateSelector : DataTemplateSelector
{
public ResourceDictionary ResourceDictionary { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Setting)
{
Setting registeritem = item as Setting;
if (registeritem.EditValueVar.EditType == EditType.Textfield)
return ResourceDictionary["TextboxDataTemplate"] as DataTemplate;
else if (registeritem.EditValueVar.EditType == EditType.DropDown)
return ResourceDictionary["ComboDataTemplate"] as DataTemplate;
else if (registeritem.EditValueVar.EditType == EditType.Slider)
return ResourceDictionary["SliderDataTemplate"] as DataTemplate;
else
throw new ArgumentOutOfRangeException(registeritem.EditValueVar.EditType.ToString());
}
return null;
}
}
...你在XAML中设置:
<local:SettingsDataTemplateSelector x:Key="selector">
<local:SettingsDataTemplateSelector.ResourceDictionary>
<ResourceDictionary Source="Dictionary1.xaml" />
</local:SettingsDataTemplateSelector.ResourceDictionary>
</local:SettingsDataTemplateSelector>
答案 1 :(得分:1)
在分开的DataTemplate
中定义ResourceDictionary
,然后将其添加到App.xaml
:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources/MyDataTemplate.xaml" />
</ResourceDictionary.MergedDictionaries>
在DataTemplateSelector
中,您可以通过以下方式获取模板:
Application.Current.FindResource("myCustomDataTemplate") as DataTemplate;
其中myCustomDataTemplate
是您在MyDataTemplate.xaml
文件中指定的datatemplate的关键字。