欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF自定义控件ComboboxTree开发

程序员文章站 2022-03-04 10:50:56
...

首先,先要创建一个wpf的自定义控件类MyComboboxTree

然后继承修改为Combobox,当然也可以继承control,不过ComboboxTree可以复用Combobox很多属性。

接着添加一个依赖属性,MyItemsSource用来给tree绑定。

代码如下:

[TemplatePart(Name = "tree", Type = typeof(TreeView))]
    [TemplatePart(Name = "PART_Popup", Type = typeof(Popup))]
    [TemplatePart(Name = "PART_TextBlock", Type = typeof(TextBlock))]
    public class MyComboboxTree : ComboBox
    {
        static MyComboboxTree()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(MyComboboxTree), new FrameworkPropertyMetadata(typeof(MyComboboxTree)));
        }

        private TreeView _tree;
        private Popup _popup;
        private TextBlock _textBlock;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _tree = GetTemplateChild("tree") as TreeView;
            _popup = GetTemplateChild("PART_Popup") as Popup;
            _textBlock = GetTemplateChild("PART_TextBlock") as TextBlock;
            _tree.MouseDoubleClick += new MouseButtonEventHandler(_tree_MouseDoubleClick);
        }

        void _tree_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var node = this._tree.SelectedItem as Node;
            if (node != null)
            {
                this._textBlock.Text = node.Name;
                _popup.IsOpen = false;
            }
        }

        public static readonly DependencyProperty MyItemsSourceProperty =
           DependencyProperty.Register("MyItemsSource", typeof(IEnumerable), typeof(MyComboboxTree),
               new FrameworkPropertyMetadata(null,
                   new PropertyChangedCallback(OnMyItemsSourceChanged)));

        public IEnumerable MyItemsSource
        {
            get { return (IEnumerable)GetValue(MyItemsSourceProperty); }
            set { SetValue(MyItemsSourceProperty, value); }
        }

        private static void OnMyItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            //var control = d as MyComboboxTree;
            //if (control != null&&control._tree!=null)
            //{
            //    control._tree.ItemsSource = e.NewValue as IEnumerable;
            //}
        }
    }

然后需要开始修改xmal中的Template了

找到生成自定义控件时生成的Generic.xaml,添加如下Template

<Style TargetType="{x:Type local:MyComboboxTree}">
        <Setter Property="FocusVisualStyle" Value="{StaticResource ComboBoxFocusVisual}"/>
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}"/>
        <Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
        <Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="Padding" Value="4,3"/>
        <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
        <Setter Property="ScrollViewer.PanningMode" Value="Both"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:MyComboboxTree}">
                    <Grid x:Name="MainGrid" SnapsToDevicePixels="true">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
                        </Grid.ColumnDefinitions>
                        <Popup x:Name="PART_Popup" AllowsTransparency="true" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
                            <Microsoft_Windows_Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=MainGrid}">
                                <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                                    <ScrollViewer x:Name="DropDownScrollViewer">
                                        <Grid RenderOptions.ClearTypeHint="Enabled">
                                            <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                                <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                                                <TreeView Height="{Binding ActualHeight, ElementName=OpaqueRect}" x:Name="tree"
                                                              ItemsSource="{TemplateBinding MyItemsSource}" 
                                                              Width="{Binding ActualWidth, ElementName=OpaqueRect}"
                                                              VerticalAlignment="Stretch" ItemContainerStyle="{DynamicResource TreeViewItemStyle1}">
                                                    <TreeView.ItemTemplate>
                                                        <HierarchicalDataTemplate DataType="{x:Type local:Node}" ItemsSource="{Binding ChildNodes}">
                                                            <TextBlock Text="{Binding Name}"/>
                                                        </HierarchicalDataTemplate>
                                                    </TreeView.ItemTemplate>
                                                </TreeView>
                                            </Canvas>
                                        </Grid>
                                    </ScrollViewer>
                                </Border>
                            </Microsoft_Windows_Themes:SystemDropShadowChrome>
                        </Popup>
                        <ToggleButton BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ComboBoxReadonlyToggleButton}"/>
                        <!--<ContentPresenter ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Content="{TemplateBinding SelectionBoxItem}" ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="false" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>-->
                        <TextBlock x:Name="PART_TextBlock" 
                                   HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                   IsHitTestVisible="false" Margin="{TemplateBinding Padding}" 
                                   SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" 
                                   VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true">
                            <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                            <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
                        </Trigger>
                        <Trigger Property="HasItems" Value="false">
                            <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
                        </Trigger>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            <Setter Property="Background" Value="#FFF4F4F4"/>
                        </Trigger>
                        <Trigger Property="IsGrouping" Value="true">
                            <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
                        </Trigger>
                        <Trigger Property="ScrollViewer.CanContentScroll" SourceName="DropDownScrollViewer" Value="false">
                            <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
                            <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

最后效果如下:

WPF自定义控件ComboboxTree开发