WPF自定義TreeView控件樣式實現(xiàn)QQ聯(lián)系人列表效果
一、前言
TreeView這個控件對于我來說是用得比較多的,以前做的小聊天軟件(好友列表)、音樂播放器(播放列表)、類庫展示器(樹形類結(jié)構(gòu))等都用的是TreeView,普通的TreeView并不能滿足我們的需求。因此我們需要滴對TreeView進(jìn)行改造。下面的內(nèi)容將介紹仿QQ聯(lián)系人TreeView樣式及TreeView數(shù)據(jù)綁定方法。
二、TreeView仿QQ聯(lián)系人列表
準(zhǔn)確的說不是仿QQ聯(lián)系人列表,這個TreeView樣式作為組織架構(gòu)來使用更好。廢話不多說,先看效果:
2.1、基本思路
像這種聯(lián)系人列表一般涉及到多層級數(shù)據(jù),而且有很多數(shù)據(jù)是需要動態(tài)更新的,如果通過手動一條條增加數(shù)據(jù)反而更復(fù)雜,而且不方便。因此為了綁定數(shù)據(jù)方便我們使用分層模板HierarchicalDataTemplate。
分層模板中存在兩種樣式,一種是分組樣式,一種是人員樣式。不管是分組還是人員綁定的都是對象,這樣我們在對象中添加一個屬性來辨別是否為分組-IsGrouping。
默認(rèn)的TreeView控件四周會有邊距,因此需要設(shè)置下TreeView的樣式。另外鼠標(biāo)經(jīng)過和鼠標(biāo)選中的背景色需要變化,因此還需要設(shè)置TreeViewItem的樣式。
根據(jù)思路,我們需要設(shè)置三個樣式,TreeView樣式,TreeViewItem樣式,HierarchicalDataTemplate分層模板樣式。另外為了自動計算下一級的邊距,我們需要添加一個轉(zhuǎn)換器IndentConverter。還需要一個轉(zhuǎn)換器需要將布爾類型的IsGrouping轉(zhuǎn)換為Visibility,還需要一個轉(zhuǎn)換器來對Visibility取反。
這樣三個樣式,三個轉(zhuǎn)換器。就可以實現(xiàn)我們上面的效果,另外還可以進(jìn)行動態(tài)數(shù)據(jù)綁定。
2.2、樣式代碼
HierarchicalDataTemplate分層模板樣式代碼
<HierarchicalDataTemplate x:Key="ItemNode" ItemsSource="{Binding Children,Mode=TwoWay}">
   <Grid Background="Transparent">
    <Grid.Resources>
     <convert:BoolToVisible x:Key="boolToVisible"/>
     <convert:VisibleToReverse x:Key="visibleToReverse"/>
    </Grid.Resources>
    <Grid MinHeight="30" x:Name="userinfo" Background="Transparent" Margin="-5 0 0 0" Visibility="{Binding Visibility,ElementName=groupinginfo,Converter={StaticResource visibleToReverse}}">
     <Grid Height="50" x:Name="grid">
      <Border Background="#62acf9" Width="40" Height="40" CornerRadius="4" HorizontalAlignment="Left" Margin="0 0 0 0">
       <TextBlock Text="{Binding SurName}" FontSize="23" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center"/>
      </Border>
      <TextBlock Text="{Binding Name}" Margin="50 7 0 0" FontSize="13"/>
      <TextBlock Text="{Binding Info}" Foreground="#808080" Margin="50 30 0 0"/>
      <TextBlock Text="{Binding Count,StringFormat={}{0}人}" Foreground="#808080" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0 0 5 0"/>
     </Grid>
    </Grid>
    <StackPanel MinHeight="25" x:Name="groupinginfo" Orientation="Horizontal" Background="Transparent" HorizontalAlignment="Left" Visibility="{Binding IsGrouping,Converter={StaticResource boolToVisible}}">
     <TextBlock Text="{Binding DisplayName}" Margin="3 0" VerticalAlignment="Center" HorizontalAlignment="Left"/>
    </StackPanel>
   </Grid>
  </HierarchicalDataTemplate>
TreeViewItem樣式代碼
<Style x:Key="DefaultTreeViewItem" TargetType="{x:Type TreeViewItem}">
   <Setter Property="MinHeight" Value="25" />
   <Setter Property="Background" Value="Transparent" />
   <Setter Property="SnapsToDevicePixels" Value="True" />
   <Setter Property="Margin" Value="0" />
   <Setter Property="Template">
    <Setter.Value>
     <ControlTemplate TargetType="{x:Type TreeViewItem}">
      <ControlTemplate.Resources>
       <convert:IndentConverter x:Key="indentConverter"/>
      </ControlTemplate.Resources>
      <Grid Background="Transparent">
       <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
       </Grid.RowDefinitions>
       <Border Name="itemBackground" Background="{TemplateBinding Background}" 
        BorderBrush="{TemplateBinding BorderBrush}" 
        BorderThickness="{TemplateBinding BorderThickness}" 
        Padding="{TemplateBinding Padding}">
        <Grid Background="Transparent">
         <Grid x:Name="ItemRoot" Margin="{Binding Converter={StaticResource indentConverter},RelativeSource={RelativeSource TemplatedParent}}" Background="Transparent">
          <Grid.ColumnDefinitions>
           <ColumnDefinition Width="16" />
           <ColumnDefinition Width="*"/>
          </Grid.ColumnDefinitions>
          <ToggleButton x:Name="Expander" HorizontalAlignment="Left" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}">
           <ToggleButton.Style>
            <Style TargetType="{x:Type ToggleButton}">
             <Setter Property="Focusable" Value="False"/>
             <Setter Property="Width" Value="16"/>
             <Setter Property="Height" Value="16"/>
             <Setter Property="Template">
              <Setter.Value>
               <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border Background="Transparent" Height="16" Padding="5" Width="16">
                 <Path x:Name="ExpandPath" Data="M0,0 L0,6 L6,0 z" Fill="#66645e" Stroke="#66645e">
                  <Path.RenderTransform>
                   <RotateTransform Angle="135" CenterY="3" CenterX="3"/>
                  </Path.RenderTransform>
                 </Path>
                </Border>
                <ControlTemplate.Triggers>
                 <Trigger Property="IsChecked" Value="True">
                  <Setter Property="RenderTransform" TargetName="ExpandPath">
                   <Setter.Value>
                    <RotateTransform Angle="180" CenterY="3" CenterX="3"/>
                   </Setter.Value>
                  </Setter>
                  <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                  <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                 </Trigger>
                 <Trigger Property="IsMouseOver" Value="True">
                  <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                  <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                 </Trigger>
                 <MultiTrigger>
                  <MultiTrigger.Conditions>
                   <Condition Property="IsMouseOver" Value="True"/>
                   <Condition Property="IsChecked" Value="True"/>
                  </MultiTrigger.Conditions>
                  <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                  <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                 </MultiTrigger>
                </ControlTemplate.Triggers>
               </ControlTemplate>
              </Setter.Value>
             </Setter>
            </Style>
           </ToggleButton.Style>
          </ToggleButton>
          <ContentPresenter Grid.Column="1" x:Name="PART_Header" ContentSource="Header" 
             HorizontalAlignment="Stretch" >
          </ContentPresenter>
         </Grid>
        </Grid>
       </Border>
       <ItemsPresenter x:Name="ItemsHost" Grid.Row="1"/>
      </Grid>
      <ControlTemplate.Triggers>
       <DataTrigger Binding="{Binding IsGrouping}" Value="false">
        <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
       </DataTrigger>
       <Trigger Property="HasItems" Value="False">
        <Setter Property="Visibility" TargetName="Expander" Value="Collapsed"/>
       </Trigger>
       <Trigger Property="IsExpanded" Value="False">
        <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
       </Trigger>
       <Trigger Property="IsSelected" Value="True">
        <Setter Property="Background" TargetName="itemBackground" Value="#FAE388"/>
       </Trigger>
       <MultiTrigger>
        <MultiTrigger.Conditions>
         <Condition Property="IsFocused" Value="False"/>
         <Condition SourceName="itemBackground" Property="IsMouseOver" Value="true"/>
        </MultiTrigger.Conditions>
        <Setter Property="Background" Value=" #fceeb9" TargetName="itemBackground"/>
       </MultiTrigger>
       <Trigger Property="IsEnabled" Value="False">
        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
       </Trigger>
      </ControlTemplate.Triggers>
     </ControlTemplate>
    </Setter.Value>
   </Setter>
  </Style>
TreeView樣式代碼
<Style x:Key="DefaultTreeView" TargetType="{x:Type TreeView}">
   <Setter Property="ScrollViewer.CanContentScroll" Value="True" />
   <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"></Setter>
   <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Recycling" />
   <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False" />
   <Setter Property="ItemContainerStyle" Value="{StaticResource DefaultTreeViewItem}"></Setter>
   <Setter Property="Padding" Value="0"/>
   <Setter Property="ItemsPanel">
    <Setter.Value>
     <ItemsPanelTemplate>
      <VirtualizingStackPanel IsItemsHost="True" Margin="0"/>
     </ItemsPanelTemplate>
    </Setter.Value>
   </Setter>
  </Style>
2.3、轉(zhuǎn)換器代碼
public class IndentConverter : IValueConverter
 {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
   double colunwidth = 10;
   double left = 0.0;
   UIElement element = value as TreeViewItem;
   while (element.GetType() != typeof(TreeView))
   {
    element = (UIElement)VisualTreeHelper.GetParent(element);
    if (element.GetType() == typeof(TreeViewItem))
     left += colunwidth;
   }
   return new Thickness(left, 0, 0, 0);
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
   throw new NotImplementedException();
  }
 }
 public class BoolToVisible : IValueConverter
 {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
   if ((bool)value)
    return Visibility.Visible;
   else
    return Visibility.Collapsed;
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
   throw new NotImplementedException();
  }
 }
 public class VisibleToReverse : IValueConverter
 {
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
   if ((Visibility)value == Visibility.Visible)
    return Visibility.Collapsed;
   else
    return Visibility.Visible;
  }
  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
   throw new NotImplementedException();
  }
 }
2.4、引用示例
 <TreeView x:Name="TreeViewOrg" BorderThickness="1" BorderBrush="#BBB" Background="Transparent" Width="280" Height="500" Margin="10" ItemTemplate="{StaticResource ItemNode}" Style="{StaticResource DefaultTreeView}">
   </TreeView>
2.5、初始化數(shù)據(jù)源及綁定對象
public MainWindow()
  {
   InitializeComponent();
   OrgList = new ObservableCollection<OrgModel>()
   {
    new OrgModel()
    {
     IsGrouping=true,
     DisplayName="單位名稱(3/7)",
     Children=new ObservableCollection<OrgModel>()
     {
      new OrgModel(){
       IsGrouping=true,
       DisplayName="未分組聯(lián)系人(2/4)",
       Children=new ObservableCollection<OrgModel>()
       {
        new OrgModel(){
         IsGrouping=false,
         SurName="劉",
         Name="劉棒",
         Info="我要走向天空!",
         Count=3
        }
       }
      }
     },
    }
   };
   TreeViewOrg.ItemsSource = OrgList;
  }
  public ObservableCollection<OrgModel> OrgList { get; set; }
  public class OrgModel
  {
   public bool IsGrouping { get; set; }
   public ObservableCollection<OrgModel> Children { get; set; }
   public string DisplayName { get; set; }
   public string SurName { get; set; }
   public string Name { get; set; }
   public string Info { get; set; }
   public int Count { get; set; }
  }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對我們的支持。
上一篇:C#對Word文檔的創(chuàng)建、插入表格、設(shè)置樣式等操作實例
欄 目:C#教程
下一篇:如何利用Jenkins + TFS為.Net Core實現(xiàn)持續(xù)集成/部署詳解
本文標(biāo)題:WPF自定義TreeView控件樣式實現(xiàn)QQ聯(lián)系人列表效果
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5196.html
您可能感興趣的文章
- 01-10C#自定義簽名章實現(xiàn)方法
 - 01-10WinForm實現(xiàn)自定義右下角提示效果的方法
 - 01-10C#實現(xiàn)自定義windows系統(tǒng)日志的方法
 - 01-10C#自定義事件監(jiān)聽實現(xiàn)方法
 - 01-10C#編程實現(xiàn)自定義熱鍵的方法
 - 01-10C#搜索TreeView子節(jié)點,保留父節(jié)點的方法
 - 01-10C#及WPF獲取本機(jī)所有字體和顏色的方法
 - 01-10C#中TreeView實現(xiàn)適合兩級節(jié)點的選中節(jié)點方法
 - 01-10C#實現(xiàn)TreeView節(jié)點拖拽的方法
 - 01-10WPF實現(xiàn)類似360安全衛(wèi)士界面的程序源碼分享
 


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
 - 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
 - 01-10WinForm限制窗體不能移到屏幕外的方法
 - 01-10WinForm繪制圓角的方法
 - 01-10C#實現(xiàn)txt定位指定行完整實例
 - 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
 - 01-10C#停止線程的方法
 - 01-10C#實現(xiàn)清空回收站的方法
 - 01-10C#通過重寫Panel改變邊框顏色與寬度的
 - 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
 
隨機(jī)閱讀
- 08-05DEDE織夢data目錄下的sessions文件夾有什
 - 01-11ajax實現(xiàn)頁面的局部加載
 - 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
 - 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
 - 01-10delphi制作wav文件的方法
 - 08-05織夢dedecms什么時候用欄目交叉功能?
 - 01-10C#中split用法實例總結(jié)
 - 04-02jquery與jsp,用jquery
 - 01-10使用C語言求解撲克牌的順子及n個骰子
 - 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
 


