rahul
rahul

Reputation: 91

Reusing WPF DataTemplate

I have a ListBox needs to display a checkbox/textblock combination for each Item. The items however are not in a collection but are exposed as properties (boolean/String) in a class. Which means that I cannot set the Binding property in the DataTemplate for the Item, since each Item will be bound to a different property.

Is it possible to define a DataTemplate that is not bound to any properties, and then later on define the Binding when using the DataTemplate.

In pseudocode:

<DataTemplate x:Key="ReusableDataTemplate">
    <StackPanel Orientation="Horizontal">
        <CheckBox />
        <TextBlock />
    </StackPanel>
</DataTemplate>

And later on use it as:

<ListBox>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable1}" TextBlockBinding="{Path=Enable1Text}"/>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable2}" 
TextBlockBinding="{Path=Enable2Text}"/>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable3}" TextBlockBinding="{Path=Enable3Text}"/>
</ListBox>

Upvotes: 0

Views: 547

Answers (1)

brunnerh
brunnerh

Reputation: 185553

That is what UserControls are for.

Upvotes: 5

Related Questions