Search code examples
c#wpfxamlcontentcontrol

Redraw DataTemplate of ContentControl


I have the following ContentControl:

<ContentControl 
    Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedEntry}">
    <ContentControl.ContentTemplate>
        <DataTemplate DataType="controls:HCITextListEntry">
            <controls:MyCustomControl
                Text="{Binding Text}" 
                Parameter="{Binding Parameters}"/>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

Everytime the SelectedEntry property changes, I want to redraw/reinit MyCustomControl. Actually only the properties are updated.


Solution

  • You may drop the ContentTemplate and write a converter for the Content Binding that returns a MyCustomControl instance:

    <ContentControl Content="{Binding SelectedEntry,
                              RelativeSource={RelativeSource TemplatedParent},
                              Converter={StaticResource MyCustomControlConverter}}"/>
    

    The converter:

    public class MyCustomControlConverter : IValueConverter
    {
        public object Convert(
            object value, Type targetType, object parameter, CultureInfo culture)
        {
            var control = new MyCustomControl();
    
            control.SetBinding(MyCustomControl.TextProperty,
                new Binding("Text") { Source = value });
            control.SetBinding(MyCustomControl.ParameterProperty,
                new Binding("Parameters") { Source = value });
    
            return control;
        }
    
        public object ConvertBack(
            object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }