为控件动态添加Style

此文可解决:  重写控件时,给控件加入子控件或父控件的样式切换问题。 很灵活的可以根据不同内容显示不同样式

 

子控件作用在:

 <DataTemplate x:Key="ColmunHeader1">
                <DockPanel Background="Transparent">
                    <!-- The control to host the filter UI for this column -->
                    <controls:dgDataGrid DockPanel.Dock="Right" />
                    <ContentPresenter x:Name="PART_Content" Content="{Binding}"
                        SnapsToDevicePixels="{Binding SnapsToDevicePixels, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridColumnHeader}}"
                        HorizontalAlignment="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridColumnHeader}}"
                        VerticalAlignment="{Binding VerticalContentAlignment, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGridColumnHeader}}" />
                </DockPanel>
            </DataTemplate>

 

如下样式:

<ControlTemplate x:Key="DataGridCheckBoxColumn1">
                <Grid>
                    <CheckBox 
                />
                </Grid>
</ControlTemplate>

<ControlTemplate x:Key="DataGridTextBoxColumn1">
                <Grid>
                    <TextBox/> 
        </Grid>
</ControlTemplate>
 

然后在子控件类的loaded事件中加入:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace WpfApp1.Controls
{
    public class dgDataGrid : Control
    {
        public DataGridColumnHeader ColumnHeader { get; set; }

        public dgDataGrid()
        {
            this.Loaded += (s, e) =>
              {
                  ColumnHeader = this.FindAncestorOrSelf<DataGridColumnHeader>();
                  var value = ColumnHeader.Column.GetType();
                  if (value == typeof(DataGridTextColumn))
                  {
                      this.Template = this.FindResource("DataGridTextColumn1") as ControlTemplate;
                  }
                  else
                  {
                      this.Template = this.FindResource("DataGridCheckBoxColumn1") as ControlTemplate;
                  }
              };
        }
    }
}

  

 

posted @ 2018-11-22 14:31  Index_Zero  阅读(516)  评论(0编辑  收藏  举报