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.)
我想过两种解决这个问题的方法.
DataTemplate.建议?
我讨厌回答自己的问题,但为了完整起见,这是我的解决方案。
<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 内部,其中每列可能以类似的方式显示,但绑定到不同的属性。