Wpf – In WPF how to change a DataTemplate’s Textblock’s text binding in code


I have a ListBox whose ItemsSource is bound to a list of objects. The Listbox has a ItemTemplate with a DataTemplate containing a TextBlock. The textblock's Text is bound to the object's Name property (i.e. Text="{Binding Name}").

I would like to provide a radio button to show different views of the same list. For example allow a user to toggle between the Name property and an ID property.

I found a SO answer for this at 2381740 but I also have border and a textbox style set in data template (see code below).

Is there anyway to just reset the Textblock binding? I don't want to have to recreate the entire datatemplate. Actually I'm not even sure how to do that, is there an easy way to translating xaml to code?.


  <Border Margin="0 0 2 2"
      <TextBlock Style="{StaticResource listBoxItemStyle}"
                 Text="{Binding Name}" />

Best Solution

Wallstreet Programmer's solution works well for you because you are using radio buttons. However there is a more general solution that I thought I should mention for future readers of this question.

You can change your DataTemplate to use plain "{Binding}"

<DataTemplate x:Key="ItemDisplayTemplate">
  <Border ...> 
    <TextBlock ...
               Text="{Binding}" /> 

Then in code you don't have to recreate a full DataTemplate. All you have to do is recreate this:

  <ContentPresenter Content="{Binding Name}" ContentTemplate="{StaticResource ItemDisplayTemplate}" />

which is easy:

private DataTemplate GeneratePropertyBoundTemplate(string property, string templateKey)
  var template = FindResource(templateKey);
  FrameworkElementFactory factory = new FrameworkElementFactory(typeof(ContentPresenter)); 
  factory.SetValue(ContentPresenter.ContentTemplateProperty, template);
  factory.SetBinding(ContentPresenter.ContentProperty, new Binding(property)); 
  return new DataTemplate { VisualTree = factory }; 

This is particularly convenient if you have many properties, even in your radio button example.

Related Question