使用ControlTemplate和ContentPresenter自定义DataGrid控件

时间:2017-09-06 02:21:39

标签: c# wpf datagrid contentpresenter contenttemplate

我有一个自定义DataGrid(我对其进行了扩展并添加了DependencyProperty Label),我正在使用DataGrid并希望添加Label控件使用ControlTemplateContentPresenter。在ContentTemplate DependencyProperty Label中可以正常显示,但ContentPresenter不起作用或根本不显示任何DataGrid控件。我尝试使用ItemsPresenter并显示行,我想知道是否有办法以这种方式使用DataGrid显示ContentPresenter?这样做的正确方法是什么?

MyUserControl.xaml

<UserControl
    x:Class="MyNamespace.UI.MyUserControl"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:e="clr-namespace:MyNamespace.UI"
     mc:Ignorable="d" 
     d:DesignHeight="350" d:DesignWidth="400">
    <UserControl.Resources>
        <Style TargetType="{x:Type e:DataGrid}"  BasedOn="{StaticResource {x:Type DataGrid}}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type e:DataGrid}">
                        <StackPanel>
                            <Label Content="{Binding Label, RelativeSource={RelativeSource TemplatedParent}}" ContentStringFormat="{}{0}: " />
                            <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </StackPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>
    <WrapPanel  x:Name="LayoutRoot" Width="900" HorizontalAlignment="Stretch" Margin="12" VerticalAlignment="Stretch">
        <e:DataGrid Label="My Label 1"     ItemsSource="{Binding Source={StaticResource MySource1}}"/>
        <e:DataGrid Label="My Label 2"     ItemsSource="{Binding Source={StaticResource MySource2}}"/>
    </WrapPanel>
</UserControl>

DataGrid.cs

namespace MyNamespace.UI
{
    public class DataGrid : System.Windows.Controls.DataGrid
    {
        public string Label
        {
            get { return (string)GetValue(LabelProperty); }
            set { SetValue(LabelProperty, value); }
        }

        public static readonly DependencyProperty LabelProperty =
            DependencyProperty.Register("Label", typeof(string), typeof(DataGrid), new UIPropertyMetadata(""));

        public DataGrid()
        {}
    }
}

1 个答案:

答案 0 :(得分:1)

ControlTemplate定义整个控件的外观。因此,您只需在模板中添加<ContentPresenter />即可显示DataGrid。此外,您不能仅继承{​​{1}}的一部分:

WPF: Is there a way to override part of a ControlTemplate without redefining the whole style?

您可以复制整个默认模板,然后将ControlTemplate添加到其中:

Label