WPF样式/模板仅应用于最后添加的元素

我有一个从ContentControl派生的简单控件,代码如下:

 public class HeaderFooterControl : ContentControl { static HeaderFooterControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderFooterControl), new FrameworkPropertyMetadata(typeof(HeaderFooterControl))); } public object Header { get { return (object)GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } } // Using a DependencyProperty as the backing store for Header. This enables animation, styling, binding, etc... public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(object), typeof(HeaderFooterControl)); public object Footer { get { return (object)GetValue(FooterProperty); } set { SetValue(FooterProperty, value); } } // Using a DependencyProperty as the backing store for Footer. This enables animation, styling, binding, etc... public static readonly DependencyProperty FooterProperty = DependencyProperty.Register("Footer", typeof(object), typeof(HeaderFooterControl)); public string HeaderText { get { return (string)GetValue(HeaderTextProperty); } set { SetValue(HeaderTextProperty, value); } } // Using a DependencyProperty as the backing store for HeaderText. This enables animation, styling, binding, etc... public static readonly DependencyProperty HeaderTextProperty = DependencyProperty.Register("HeaderText", typeof(string), typeof(HeaderFooterControl)); public string FooterText { get { return (string)GetValue(FooterTextProperty); } set { SetValue(FooterTextProperty, value); } } // Using a DependencyProperty as the backing store for FooterText. This enables animation, styling, binding, etc... public static readonly DependencyProperty FooterTextProperty = DependencyProperty.Register("FooterText", typeof(string), typeof(HeaderFooterControl)); } 

它具有可自定义的页眉和页脚属性,因此用户可以在其中附加任何控件。

此应用程序中唯一的窗口定义如下:

                                               

此窗口的资源为我的自定义控件定义了2种样式。 自定义控件显示标题,主要内容和页脚。 默认情况下,页眉/页脚是TextBlock ,其Text属性绑定到HeaderTextHeaderFooterControl FooterText属性。 问题是只有最后添加的HeaderFooterControl才会显示任何内容。 为什么会这样?

到目前为止,我发现的唯一解决方案是将页眉和页脚部分的内容移动到资源中,然后使用StaticResource扩展从xaml代码引用这些资源。 所有内容都是UIElement因此每个实例都应该设置x:Shared="False"属性,以便在VisualTree中每次需要时创建它。 还看看这个答案,它暗示了相同的行为描述https://stackoverflow.com/a/8702180/371967