Wpf

WPF TreeView с CheckBox, икона

Wpf Treeview With Checkbox



В действителното разработване на проекти на WPF, TreeView с CheckBox често се използва. Въпреки че Microsoft не предоставя тази функция в WPF TreeView, Microsoft предоставя мощна функция за шаблон на шаблон и персонализиран стил в WPF, тогава можем да я напишем сами. Един такъв контрол е за ваша собствена употреба.

Това е просто, което сам написах.



Първо напишете модел на данни за TreeView и внедрете интерфейса INotifyPropertyChanged.Използва се за издаване на известие, че стойността на свойството е променена на клиент (обикновено клиент, който извършва обвързване).Когато свойството се промени, съответната производителност на потребителския интерфейс също се променя. Основни полета Id, Name, Icon, ToolTip, IsChecked, IsExpanded, Parent, Children



изображение
//*************************************************** // // File name (FileName) : TreeModel.cs // // Author (Author) : zsm // // CreateTime: 2013-03-18 14:23:58 // // Description: A data model for TreeView. // //*************************************************** using System using System.Collections.Generic using System.Linq using System.Text using System.ComponentModel namespace Com.FMS.Model { public class TreeModel : INotifyPropertyChanged { #region Private variable ///  /// Id value ///  private string _id ///  /// Displayed name ///  private string _name ///  /// Icon path ///  private string _icon ///  /// Selected state ///  private bool _isChecked ///  /// Folded state ///  private bool _isExpanded ///  /// Child ///  private IList _children ///  /// Parent ///  private TreeModel _parent #endregion ///  /// Construction ///  public TreeModel() { Children = new List() _isChecked = false IsExpanded = false _icon = '/Images/16_16/folder_go.png' } ///  /// Key value ///  public string Id { get { return _id } set { _id = value } } ///  /// Displayed characters ///  public string Name { get { return _name } set { _name = value } } ///  /// Icon ///  public string Icon { get { return _icon } set { _icon = value } } ///  /// Display instructions when the pointer is hovered ///  public string ToolTip { get { return String.Format('{0}-{1}', Id, Name) } } ///  /// Whether to select ///  public bool IsChecked { get { return _isChecked } set { if (value != _isChecked) { _isChecked = value NotifyPropertyChanged('IsChecked') if (_isChecked) { //If checked, the parent should also be selected if (Parent != null) { Parent.IsChecked = true } } else { //If you uncheck the subkey, you should also uncheck it. foreach (TreeModel child in Children) { child.IsChecked = false } } } } } ///  /// Whether to expand ///  public bool IsExpanded { get { return _isExpanded } set { if (value != _isExpanded) { //Folding state change _isExpanded = value NotifyPropertyChanged('IsExpanded') } } } ///  /// Parent ///  public TreeModel Parent { get { return _parent } set { _parent = value } } ///  /// Child ///  public IList Children { get { return _children } set { _children = value } } ///  /// Set the selected state of all children ///  ///  public void SetChildrenChecked(bool isChecked) { foreach (TreeModel child in Children) { child.IsChecked = IsChecked child.SetChildrenChecked(IsChecked) } } ///  /// Set all child expansion states ///  ///  public void SetChildrenExpanded(bool isExpanded) { foreach (TreeModel child in Children) { child.IsExpanded = isExpanded child.SetChildrenExpanded(isExpanded) } } ///  /// Attribute change event ///  public event PropertyChangedEventHandler PropertyChanged private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)) } } } }
изображение

Създайте потребителски контрол, съдържащ основно TreeView контрола, ContextMenu щракнете с десния бутон върху менюто, кодът на потребителския интерфейс е както следва (пътят трябва да бъде модифициран според действителния):



изображение
<UserControl x:Class='Com.FMS.View.UserControls.ZsmTreeView' 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:local='clr-namespace:Com.FMS.Model' mc:Ignorable='d' d:DesignHeight='300' d:DesignWidth='300'> <Grid> <DockPanel> <Border DockPanel.Dock='Bottom'> <StackPanel Orientation='Horizontal' ToolTip='Right has more features!'> <Image Height='16' Width='16' Source='Images/16_16/emoticon_smile.png'>Image> <Label Content='Right has more features!' Foreground='Gray'>Label> StackPanel> Border> <Border> <TreeView Name='tvZsmTree'> <TreeView.ContextMenu> <ContextMenu> <MenuItem Name='menuExpandAll' Header='All expansion' Click='menuExpandAll_Click'> <MenuItem.Icon> <Image Source='/Com.FMScomponent/Images/16_16/folder_open_arrow.png' /> MenuItem.Icon> MenuItem> <MenuItem Name='menuUnExpandAll' Header='all folded' Click='menuUnExpandAll_Click'> <MenuItem.Icon> <Image Source='/Com.FMScomponent/Images/16_16/folder_close_arrow.png' /> MenuItem.Icon> MenuItem> <MenuItem Name='menuSelectAll' Header='Select all' Click='menuSelectAll_Click'> <MenuItem.Icon> <Image Source='/Com.FMScomponent/Images/16_16/tick.png' /> MenuItem.Icon> MenuItem> <MenuItem Name='menuUnSelectAll' Header='all canceled' Click='menuUnSelectAll_Click'> <MenuItem.Icon> <Image Source='/Com.FMScomponent/Images/16_16/delete.png' /> MenuItem.Icon> MenuItem> ContextMenu> TreeView.ContextMenu> <TreeView.ItemContainerStyle> <Style TargetType='TreeViewItem'> <Setter Property='IsExpanded' Value='{Binding IsExpanded, Mode=TwoWay}'>Setter> <EventSetter Event='TreeViewItem.PreviewMouseRightButtonDown' Handler='TreeViewItem_PreviewMouseRightButtonDown'/> Style> TreeView.ItemContainerStyle> <TreeView.ItemTemplate> <HierarchicalDataTemplate DataType='{x:Type local:TreeModel}' ItemsSource='{Binding Children}'> <StackPanel Margin='-2,0,0,0' Orientation='Horizontal' x:Name='staTree'> <CheckBox ToolTip='{Binding ToolTip}' FontSize='14' FontFamily='Microsoft Yahei' Tag='{Binding Children}' IsChecked='{Binding IsChecked, Mode=TwoWay}'> <StackPanel Orientation='Horizontal'> <Image VerticalAlignment='Center' Source='{Binding Icon}' >Image> <TextBlock Text='{Binding Name}'>TextBlock> StackPanel> <CheckBox.ContextMenu> <ContextMenu> <MenuItem Name='menuSelectAllChild' Header='All selected items' Click='menuSelectAllChild_Click'> <MenuItem.Icon> <Image Source='/Com.FMScomponent/Images/16_16/tick.png' /> MenuItem.Icon> MenuItem> ContextMenu> CheckBox.ContextMenu> CheckBox> StackPanel> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding='{Binding IsChecked}' Value='true'> <Setter TargetName='staTree' Property='Background' Value='White'/> DataTrigger> HierarchicalDataTemplate.Triggers> HierarchicalDataTemplate> TreeView.ItemTemplate> TreeView> Border> DockPanel> Grid> UserControl>
изображение

В кода на логиката за взаимодействие има предимно контролни данни PropertiesSourceData свойство, задайте съответния Id елемент в избраното състояние SetCheckedById, игнорирайте йерархичната връзка, вземете избрания елемент CheckedItemsIgnoreRelation и т.н. и щракнете с десния бутон върху избраното меню от всички елементи, всички избрани, всички махнете отметката, свийте, разгънете всички и т.н. Интерактивният логически код е:

изображение
//*************************************************** // // File name (FileName): ZsmTreeView.xaml.cs // // Author (Author) : zsm // // CreateTime: 2013-03-15 16:52:40 // // Description: Interactive logic code for the TreeView control with CheckBox // //*************************************************** using System using System.Collections.Generic using System.Linq using System.Text using System.Windows using System.Windows.Controls using System.Windows.Data using System.Windows.Documents using System.Windows.Input using System.Windows.Media using System.Windows.Media.Imaging using System.Windows.Navigation using System.Windows.Shapes namespace Com.FMS.View.UserControls { ///  /// Interaction logic of ZsmTreeView.xaml ///  public partial class ZsmTreeView : UserControl { #region Private variable attribute ///  /// Control data ///  private IList _itemsSourceData #endregion ///  /// Construction ///  public ZsmTreeView() { InitializeComponent() } ///  /// Control data ///  public IList ItemsSourceData { get { return _itemsSourceData } set { _itemsSourceData = value tvZsmTree.ItemsSource = _itemsSourceData } } ///  /// Set the item corresponding to Id to be selected. ///  ///  ///  public int SetCheckedById(string id, IList treeList) { foreach (var tree in treeList) { if (tree.Id.Equals(id)) { tree.IsChecked = true return 1 } if (SetCheckedById(id, tree.Children) == 1) { return 1 } } return 0 } ///  /// Set the item corresponding to Id to be selected. ///  ///  ///  public int SetCheckedById(string id) { foreach (var tree in ItemsSourceData) { if (tree.Id.Equals(id)) { tree.IsChecked = true return 1 } if (SetCheckedById(id, tree.Children) == 1) { return 1 } } return 0 } ///  /// Get selected items ///  ///  public IList CheckedItemsIgnoreRelation() { return GetCheckedItemsIgnoreRelation(_itemsSourceData) } ///  /// Private method, get the selected item if the hierarchical relationship is ignored ///  ///  ///  private IList GetCheckedItemsIgnoreRelation(IList list) { IList treeList = new List() foreach (var tree in list) { if (tree.IsChecked) { treeList.Add(tree) } foreach (var child in GetCheckedItemsIgnoreRelation(tree.Children)) { treeList.Add(child) } } return treeList } ///  /// Check all child menu events ///  ///  ///  private void menuSelectAllChild_Click(object sender, RoutedEventArgs e) { if (tvZsmTree.SelectedItem != null) { Model.TreeModel tree = (Model.TreeModel)tvZsmTree.SelectedItem tree.IsChecked = true tree.SetChildrenChecked(true) } } ///  /// Expand menu events all ///  ///  ///  private void menuExpandAll_Click(object sender, RoutedEventArgs e) { foreach (Model.TreeModel tree in tvZsmTree.ItemsSource) { tree.IsExpanded = true tree.SetChildrenExpanded(true) } } ///  /// Full collapse menu event ///  ///  ///  private void menuUnExpandAll_Click(object sender, RoutedEventArgs e) { foreach (Model.TreeModel tree in tvZsmTree.ItemsSource) { tree.IsExpanded = false tree.SetChildrenExpanded(false) } } ///  /// All selected events ///  ///  ///  private void menuSelectAll_Click(object sender, RoutedEventArgs e) { foreach (Model.TreeModel tree in tvZsmTree.ItemsSource) { tree.IsChecked = true tree.SetChildrenChecked(true) } } ///  /// Uncheck all ///  ///  ///  private void menuUnSelectAll_Click(object sender, RoutedEventArgs e) { foreach (Model.TreeModel tree in tvZsmTree.ItemsSource) { tree.IsChecked = false tree.SetChildrenChecked(false) } } ///  /// Right mouse button event ///  ///  ///  private void TreeViewItem_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) { TreeViewItem item = VisualUpwardSearch(e.OriginalSource as DependencyObject) as TreeViewItem if (item != null) { item.Focus() e.Handled = true } } static DependencyObject VisualUpwardSearch(DependencyObject source) { while (source != null && source.GetType() != typeof(T)) source = VisualTreeHelper.GetParent(source) return source } } }
изображение

Когато използвате контроли, трябва да въведете имена на контроли в xaml (според действителното въвеждане)

xmlns:my='clr-namespace:Com.FMS.View.UserControls'
 
Присвояване на стойност на контролата:
ztvModule.ItemsSourceData = treeList//treeList is of type IList

дисплей ефект:



Всъщност можете също така да завършите общо многофункционални, изчакващи време за писане.

http://www.cnblogs.com/zsmhhfy/archive/2013/03/18/2965755.html

Препечатано на: https://www.cnblogs.com/ExMan/p/3784921.html