How can I factor out a DataTemplate's binding in WPF?
Asked Answered
C

2

12

I have a DataTemplate I want to reuse. The part I want to factor out is the binding, because it's the only thing that changes. My DataTemplate looks roughly like this. (There's actually quite a bit more to it, but I've taken out the extraneous stuff.)

<DataTemplate>
    <TextBox Text="{Binding Name}" />
</DataTemplate>

How can I reuse this DataTemplate while simply varying the property to which I'm binding? (Note that if it were as simple as just a TextBox, I wouldn't worry about it, but the DataTemplate actually contains a StackPanel with a number of other elements in it. I want to centralize that in one place, hence the DataTemplate.)

I've thought about two ways to tackle this problem.

  1. Create a simple custom control. Reuse that, and don't worry about reusing the DataTemplate.
  2. Experiment with some kind of subclass of DataTemplate. (I'm told this is possible.) I'd add a dependency property to it that lets me specify the name of the property to which I want to bind.

Suggestions?

Chufa answered 16/6, 2009 at 20:20 Comment(0)
C
4

I hate answering my own questions, but for the sake of completeness, here's my solution.

<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>

This of course is a very contrived example. In my own app, I'm not actually putting textboxes inside of a listbox. In a listbox, this is not very useful, but imagine it inside of a DataGrid, where each column might be displayed in a similar way, but binds to a different property.

Chufa answered 16/6, 2009 at 22:44 Comment(0)
T
0

Create a UserControl and use it within the DataTemplate.

<DataTemplate>
    <local:MyComplexUserControl DataContext="{Binding Name}"/>
</DataTemplate>

and within the UserControl:

<StackPanel>
  <TextBlock>Value:</Text>
  <TextBox Text="{Binding}"/>
</StackPanel>

Have a separate DataTemplate with its own binding for each occasion.

Trudy answered 17/6, 2009 at 1:1 Comment(1)
You could do this without a UserControl I expect -- just using a ControlTemplate in a resource.Peptide

© 2022 - 2024 — McMap. All rights reserved.