重绘ContentControl的DataTemplate

时间:2018-06-19 06:21:13

标签: c# wpf xaml 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属性更改时,我都想重新绘制/重新启动MyCustomControl。实际上只有属性会更新。

1 个答案:

答案 0 :(得分:1)

您可以删除ContentTemplate并为返回MyCustomControl实例的Content Binding编写转换器:

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