使用元素语法在 UserControl 上设置附加的 属性 值

Set attached property value on UserControl using element syntax

假设我在命名空间 ns 中有一个附加的 属性 "Attached.Template" 类型的 DataTemplate,我希望通过 XAML 在我的 UserControl 上设置它。有没有语法可以让我这样做?以下是一些不起作用的东西:

<!-- 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);
}

UserControl.Resources 中创建你的 DataTemplate 然后给它一个 Key,然后使用 namespace:attatchedproperty={StaticResource Key} 你将能够实现我认为你所要求的.

看来您必须像这样显式设置 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 解析器中的一个奇怪错误或缺陷。