为什么我不能在样式中设置数据模板,但我可以在控件模板中?

时间:2021-07-31 21:02:58

Why doesn't this work:

为什么这不起作用:

 <Style TargetType="s:Substance">
    <Setter Property="Template">
        <Setter.Value>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{TemplateBinding Name}"/>
                    <TextBox Text="{TemplateBinding Count}"/>
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

If I switch to ControlTemplate it works, but I need a data template. Also, if I replace Template with DataTemplate it doesn't recognize the property. Does anyone know what is going on? Thank you.

如果我切换到ControlTemplate它可以工作,但我需要一个数据模板。此外,如果我用DataTemplate替换Template,它将无法识别该属性。有谁知道发生了什么?谢谢。

NOTE: Substance derives from FrameworkElement. It is not a control.

注意:Substance派生自FrameworkElement。它不是一种控制。

1 个解决方案

#1


4  

You don't seem to know what you are doing, Template expects a ControlTemplate, this property sets the template of the control itself, not its data.

您似乎不知道自己在做什么,Template需要一个ControlTemplate,此属性设置控件本身的模板,而不是其数据。

Does your Substance control even have any property that expects a DataTemplate? e.g. ContentTemplate (if it is a ContentControl) or ItemTemplate (if it is an ItemsControl)?

您的Substance控件是否具有任何需要DataTemplate的属性?例如ContentTemplate(如果是ContentControl)或ItemTemplate(如果它是ItemsControl)?

Edit: You probably just want to do this:

编辑:您可能只想这样做:

<Some.Resources>
    <DataTemplate DataType="{x:Type s:Substance}"> <!-- The use of x:Type is important! -->
        <StackPanel>
            <TextBlock Text="{Binding Name}"/>
            <TextBox Text="{Binding Count}"/>
        </StackPanel>
    </DataTemplate>
</Some.Resources>

Which defines a datatemplate for Substance; Wherever Substance is added as content or item, that datatemplate will be automatically applied.

其中定义了物质的数据模板;无论在何处添加物质作为内容或项目,都将自动应用该数据模板。

#1


4  

You don't seem to know what you are doing, Template expects a ControlTemplate, this property sets the template of the control itself, not its data.

您似乎不知道自己在做什么,Template需要一个ControlTemplate,此属性设置控件本身的模板,而不是其数据。

Does your Substance control even have any property that expects a DataTemplate? e.g. ContentTemplate (if it is a ContentControl) or ItemTemplate (if it is an ItemsControl)?

您的Substance控件是否具有任何需要DataTemplate的属性?例如ContentTemplate(如果是ContentControl)或ItemTemplate(如果它是ItemsControl)?

Edit: You probably just want to do this:

编辑:您可能只想这样做:

<Some.Resources>
    <DataTemplate DataType="{x:Type s:Substance}"> <!-- The use of x:Type is important! -->
        <StackPanel>
            <TextBlock Text="{Binding Name}"/>
            <TextBox Text="{Binding Count}"/>
        </StackPanel>
    </DataTemplate>
</Some.Resources>

Which defines a datatemplate for Substance; Wherever Substance is added as content or item, that datatemplate will be automatically applied.

其中定义了物质的数据模板;无论在何处添加物质作为内容或项目,都将自动应用该数据模板。