如何在WPF中分解出DataTemplate的绑定?

Gre*_*ley 12 wpf xaml datatemplate

我有一个DataTemplate我想重用.我要分解的部分是绑定,因为它是唯一改变的东西.我DataTemplate看起来大致像这样.(实际上还有更多的东西,但我已经把外来的东西拿走了.)

<DataTemplate>
    <TextBox Text="{Binding Name}" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

如何DataTemplate简单地改变我绑定的属性?(请注意,如果它只是一个简单TextBox,我不会担心它,但DataTemplate实际上包含一个StackPane带有许多其他元素的l.我想将它集中在一个地方,因此DataTemplate.)

我想过两种解决这个问题的方法.

  1. 创建一个简单的自定义控件 重复使用,不要担心重复使用DataTemplate.
  2. 尝试使用某种DataTemplate子类.(我被告知这是可能的.)我将向它添加一个依赖属性,它允许我指定要绑定的属性的名称.

建议?

Gre*_*ley 4

我讨厌回答自己的问题,但为了完整起见,这是我的解决方案。

<ListBox ItemsSource="{Binding}">
  <ListBox.Resources>
    <ControlTemplate x:Key="textBoxControlTemplate" TargetType="ContentControl">
      <TextBox Text="{TemplateBinding Content}" /> 
    </ControlTemplate>
  </ListBox.Resources>
  <ListBox.ItemTemplate>
    <DataTemplate>
      <ContentControl Content="{Binding Name}" Template="{StaticResource textBoxControlTemplate}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

这当然是一个非常做作的例子。在我自己的应用程序中,我实际上并没有将文本框放入列表框中。在列表框中,这不是很有用,但想象一下它在 DataGrid 内部,其中每列可能以类似的方式显示,但绑定到不同的属性。