Search code examples
wpfdatatemplate

datatemplate not switching upon datatrigger


I have defined two datatemplates for my listBox for which I am using a DataTemplateSelector to decide which one to be rendered for an item. However, One of my templates has an embedded button which when clicked should display a form in place. So I have setup a boolean property and implemented INotifyPropertyChanged; so that when the boolean property is true, the current template is replaced by a third template.

This is the code for the button.

        Activity activityItem = (Activity)listBox1.Items[listBox1.SelectedIndex]; 
        activityItem.ShowFeedbackForm = 1;

This is my XAML:

    <Grid.Resources>
    <DataTemplate x:Key="completedActivityTemplate">
        <Grid Name="templateGrid" >
    ... 
    <DataTemplate x:Key="activityTemplate">
        <Grid Name="templateGrid" >
    ...
    <DataTemplate x:Key="feedbackFormTemplate">
        <Grid Name="templateGrid" >
    ...    
     <Style TargetType="ListBoxItem" x:Key="ContainerStyle">
        <Setter Property="Height" Value="55" />
        <Setter Property="Background" Value="Transparent" />
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="IsSelected" Value="True" />
            </Trigger>
            <DataTrigger Binding="{Binding showFeedbackForm}" Value="1">
                <Setter Property="ContentTemplate" Value="{StaticResource feedbackFormTemplate}" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
    </Grid.Resources>
    <ListBox Grid.Row="1" Name="listBox1" IsSynchronizedWithCurrentItem="True" 
         ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         VerticalContentAlignment="Stretch" Background="Transparent"
         BorderThickness="0" ItemContainerStyle="{StaticResource ContainerStyle}"
         HorizontalContentAlignment="Stretch" Margin="-3,0,0,0"
         ItemTemplateSelector="{StaticResource myDataTemplateSelector}">
    </ListBox>

So when the user clicks the button, the value of 1 is set for the ShowFeedbackForm for that item which is when the template showing a feedback form is to be displayed but nothing is happening. My ObservableCollection(one way) bindings are working fine.


Solution

  • In the button click handler, I set the boolean value the bound item and then rebind the datatemplate selector for the listBox.

            ListBoxItem currentItem = (ListBoxItem)(listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.Items.CurrentItem));
            Activity activityItem = (Activity)listBox1.Items[listBox1.SelectedIndex]; 
            activityItem.ShowFeedbackForm = 1;
            listBox1.ItemTemplateSelector = new ActivityFeedDataTemplateSelector();
    

    My ActivityFeedDataTemplateSelector returns the desired template name if the boolean is set.