假设我希望通过XAML在UserControl上设置名称空间ns中的DataTemplate类型的附加属性“ Attached.Template”。有没有让我做到这一点的语法?以下是一些无效的内容:
<!-- fails; UserControl may have only one child -->
<UserControl>
<ns:Attached.Template>
<DataTemplate />
</ns:Attached.Template>
<Grid />
</UserControl>
<!-- fails; the '(' character cannot be included in a name -->
<UserControl>
<UserControl.(ns:Attached.Template)>
<DataTemplate />
</UserControl.(ns:Attached.Template)>
<Grid />
</UserControl>
<!-- fails; "UserControl.ns" is an undeclared prefix -->
<UserControl>
<UserControl.ns:Attached.Template>
<DataTemplate />
</UserControl.ns:Attached.Template>
<Grid />
</UserControl>
属性定义非常标准;只需遵循R#的内置模板:
public static class Attached
{
public static readonly DependencyProperty TemplateProperty = DependencyProperty.RegisterAttached(
"Template", typeof(DataTemplate), typeof(Attached),
new PropertyMetadata(default(DataTemplate)));
public static void SetTemplate(DependencyObject element, DataTemplate value) =>
element.SetValue(TemplateProperty, value);
public static DataTemplate GetTemplate(DependencyObject element) =>
(DataTemplate) element.GetValue(TemplateProperty);
}
答案 0 :(得分:2)
似乎您必须像这样显式设置UserControl的Content
:
<UserControl>
<ns:Attached.Template>
<DataTemplate/>
</ns:Attached.Template>
<UserControl.Content>
<Grid/>
</UserControl.Content>
</UserControl>
这也有效:
<UserControl>
<Grid/>
<ns:Attached.Template>
<DataTemplate/>
</ns:Attached.Template>
</UserControl>
IMO XAML解析器中的怪异错误或缺陷。
答案 1 :(得分:0)
在DataTemplate
中创建UserControl.Resources
,然后给它一个Key
,然后使用namespace:attatchedproperty={StaticResource Key}
,您将能够实现我认为的要求。 / p>