将标头和内容动态绑定到扩展器

问题描述 投票:0回答:1

首先,我看到Header的类型和扩展器的内容,它说类型是对象。我有一个名为CommonExpanderUserControl的用户控件,如下所示,

xaml:

<uwpControls:Expander Header="{Binding HeaderContent}" Content="{Binding MainContent}">

</uwpControls:Expander>

在xaml.cs中(DataContext设置为此)

  public static readonly DependencyProperty HeaderContentProperty =
      DependencyProperty.Register("HeaderContent", typeof(object), typeof(CommonExpanderUserControl), new
         PropertyMetadata(null));

        public object HeaderContent
        {
            get { return (object)GetValue(HeaderContentProperty); }
            set { SetValue(HeaderContentProperty, value); }
        }


        public static readonly DependencyProperty MainContentProperty =
    DependencyProperty.Register("MainContent", typeof(ContentControl), typeof(CommonExpanderUserControl), new
       PropertyMetadata(null));

        public ContentControl MainContent
        {
            get { return (ContentControl)GetValue(MainContentProperty); }
            set { SetValue(MainContentProperty, value); }
        }

现在我正在如下所示在外部某处使用此UserControl,

<UserControl.Resources>
<ContentControl x:Key="Header">
                <Grid x:Name="ExpanderHeaderGrid" HorizontalAlignment="Stretch" Padding="0" Margin="0" 
                      Background="{Binding LisSharedSettings.ChangeHeaderColor,Converter={StaticResource BoolToSolidBrushConverter}}">
                    <TextBlock x:Name="TextBlockLisSharedSettingsTitle" 
                                   x:Uid="/Application.GlobalizationLibrary/Resources/InstrumentSettingsViewLisSettingsTextBlockTitle"
                                   Style="{StaticResource TextBlockStyleSectionHeader}"/>
                </Grid>
            </ContentControl>

<ContentControl x:Key="Body">
Some content here.
</ContentControl>
</UserControl.Resources>
<Grid>
            <local:CommonExpanderUserControl HeaderContent="{StaticResource Header}" MainContent="{StaticResource Body}"/>
</Grid>

绑定这样的内容控件根本行不通。如果我删除MainContent绑定并仅绑定Header,则表示对象引用未设置为对象的实例。请帮忙。

wpf xaml uwp expander
1个回答
0
投票

问题出现在StaticResource绑定中,我们无法通过StaticResource绑定标题与控件。对于这种情况,更好的方法是绑定StaticResource并将数据源发送到header属性,如下所示。

HeaderTemplate
© www.soinside.com 2019 - 2024. All rights reserved.