重绘 ContentControl 的 DataTemplate

Redraw DataTemplate of ContentControl

我有以下 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>

每次 SelectedEntry 属性 改变,我都想 redraw/reinit MyCustomControl。实际上只更新了属性。

您可以删除 ContentTemplate 并为 returns MyCustomControl 实例的内容绑定编写一个转换器:

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

转换器:

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();
    }
}