WPF日积月累之DataGrid样式以及操作数据模板中的控件

一、效果图

二、代码预览

  1 <Window x:Class="Test.MainWindow"
  2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6         xmlns:local="clr-namespace:Test"
  7         mc:Ignorable="d"
  8         Title="MainWindow" Height="450" Width="800">
  9     <Window.Resources>
 10         <local:Text2ImageConverter x:Key="text2ImageConverter"></local:Text2ImageConverter>
 11     </Window.Resources>
 12     <Grid Margin="10">
 13         <DataGrid Margin="3 0 3 0" Name="dataGridTestCase" ItemsSource="{Binding CaseCollection}" BorderThickness="0"
 14                               AutoGenerateColumns="False"  CanUserAddRows = "False" SelectedIndex="{Binding SelIndex,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" RowHeaderWidth="0">
 15             <DataGrid.ColumnHeaderStyle>
 16                 <Style  TargetType="DataGridColumnHeader">
 17                     <Setter Property="HorizontalContentAlignment" Value="Center"/>
 18                     <Setter Property="BorderBrush" Value="#FFA558EA"/>
 19                     <Setter Property="BorderThickness" Value="0 0.5 0.5 0.5"/>
 20                     <!--<Setter Property="Background" Value="#FF421E63"/>-->
 21                     <Setter Property="Background">
 22                         <Setter.Value>
 23                             <ImageBrush ImageSource="Resource/dgBg.png">
 24
 25                             </ImageBrush>
 26                         </Setter.Value>
 27                     </Setter>
 28                     <Setter Property="Foreground" Value="White"/>
 29                     <Setter Property="Height" Value="30"/>
 30                 </Style>
 31             </DataGrid.ColumnHeaderStyle>
 32             <DataGrid.RowStyle>
 33                 <Style TargetType="DataGridRow">
 34                     <Style.Triggers>
 35                         <Trigger Property="IsMouseOver" Value="True">
 36                             <Setter Property="Background" Value="#FFF9F0FF" >
 37
 38                             </Setter>
 39                         </Trigger>
 40                         <Trigger Property="IsSelected" Value="True">
 41                             <Setter Property="Background" Value="#FFB57EED" >
 42
 43                             </Setter>
 44                         </Trigger>
 45                     </Style.Triggers>
 46                 </Style>
 47             </DataGrid.RowStyle>
 48
 49             <DataGrid.CellStyle>
 50                 <Style TargetType="DataGridCell">
 51                     <Style.Triggers>
 52                         <Trigger Property="IsMouseOver" Value="True">
 53                             <Setter Property="Background" Value="#FFF9F0FF" >
 54
 55                             </Setter>
 56                         </Trigger>
 57                         <Trigger Property="IsSelected" Value="True">
 58                             <Setter Property="Background" Value="#FFB57EED" />
 59
 60                             <Setter Property="BorderBrush" Value="#FFB57EED" />
 61                             <Setter Property="Foreground" Value="White" />
 62
 63                         </Trigger>
 64                     </Style.Triggers>
 65                 </Style>
 66             </DataGrid.CellStyle>
 67             <DataGrid.Style>
 68                 <Style TargetType="DataGrid">
 69                     <Setter Property="BorderBrush" Value="#FFF5F7F5" />
 70                     <Setter Property="HorizontalGridLinesBrush">
 71                         <Setter.Value>
 72                             <SolidColorBrush Color="#FF532F75"/>
 73                         </Setter.Value>
 74                     </Setter>
 75                     <Setter Property="VerticalGridLinesBrush">
 76                         <Setter.Value>
 77                             <SolidColorBrush Color="#FF532F75"/>
 78                         </Setter.Value>
 79                     </Setter>
 80                 </Style>
 81             </DataGrid.Style>
 82
 83             <DataGrid.Columns >
 84                 <DataGridTemplateColumn Header=""  MinWidth="8" Width="8" MaxWidth="8">
 85                     <DataGridTemplateColumn.CellTemplate>
 86                         <DataTemplate>
 87                             <Label Name="lb" Margin="-1">
 88                                 <Label.Background>
 89                                     <ImageBrush ImageSource="Resource/dgBg.png">
 90
 91                                     </ImageBrush>
 92                                 </Label.Background>
 93                             </Label>
 94                         </DataTemplate>
 95                     </DataGridTemplateColumn.CellTemplate>
 96                 </DataGridTemplateColumn>
 97
 98                 <DataGridTemplateColumn Header="用例描述" MinWidth="373" >
 99                     <DataGridTemplateColumn.CellTemplate>
100                         <DataTemplate>
101                             <Label Content="{Binding Description}"  ToolTip="{Binding Description}"></Label>
102                         </DataTemplate>
103                     </DataGridTemplateColumn.CellTemplate>
104                 </DataGridTemplateColumn>
105
106                 <DataGridTemplateColumn Header="结果" Width="40">
107                     <DataGridTemplateColumn.CellTemplate>
108                         <DataTemplate>
109                             <Image Source="{Binding TestResult, Converter={StaticResource text2ImageConverter},ConverterParameter=0}" Width="20" Height="20"></Image>
110                         </DataTemplate>
111                     </DataGridTemplateColumn.CellTemplate>
112                 </DataGridTemplateColumn>
113                 <DataGridTemplateColumn Header="操作" Width="50" >
114                     <DataGridTemplateColumn.CellTemplate>
115                         <DataTemplate>
116                             <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
117                                 <Button Content="查看" Name="btnDetail" Width="auto" Margin="1 0 5 0" >
118                                     <Button.Style>
119                                         <Style TargetType="Button">
120                                             <Setter Property="Padding" Value="0"/>
121                                             <Setter Property="Foreground" Value="Green"/>
122                                             <Setter Property="VerticalAlignment" Value="Center"/>
123                                             <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
124                                             <Setter Property="Template">
125                                                 <Setter.Value>
126                                                     <ControlTemplate TargetType="Button">
127                                                         <ContentPresenter Content="{TemplateBinding Content}"/>
128                                                     </ControlTemplate>
129                                                 </Setter.Value>
130                                             </Setter>
131                                             <Style.Triggers>
132                                                 <Trigger  Property="IsMouseOver" Value="True">
133                                                     <Setter Property="Foreground" Value="Red">
134
135                                                     </Setter>
136                                                 </Trigger>
137                                             </Style.Triggers>
138                                         </Style>
139                                     </Button.Style>
140                                 </Button>
141                             </StackPanel>
142                         </DataTemplate>
143                     </DataGridTemplateColumn.CellTemplate>
144                 </DataGridTemplateColumn>
145             </DataGrid.Columns>
146
147         </DataGrid>
148     </Grid>
149 </Window>

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Collections.ObjectModel;
  4 using System.ComponentModel;
  5 using System.Globalization;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows;
  9 using System.Windows.Controls;
 10 using System.Windows.Data;
 11 using System.Windows.Documents;
 12 using System.Windows.Input;
 13 using System.Windows.Media;
 14 using System.Windows.Media.Imaging;
 15 using System.Windows.Navigation;
 16 using System.Windows.Shapes;
 17
 18 namespace Test
 19 {
 20
 21     /// <summary>
 22     /// MainWindow.xaml 的交互逻辑
 23     /// </summary>
 24     public partial class MainWindow : Window, INotifyPropertyChanged
 25     {
 26         #region INotifyPropertyChanged interface
 27         public event PropertyChangedEventHandler PropertyChanged;
 28         public virtual void OnPropertyChanged(string propertyName)
 29         {
 30             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 31         }
 32         #endregion
 33         public ObservableCollection<Case> CaseCollection { get; set; }
 34         private int preSelIndex = 0;
 35         private int selIndex =  -1;
 36         public int SelIndex
 37         {
 38             get
 39             {
 40                 return selIndex;
 41             }
 42             set
 43             {
 44                 if(value != selIndex)
 45                 {
 46                     selIndex = value;
 47
 48                     DataGridRow preRow = GetRow(dataGridTestCase, preSelIndex);
 49                     Label preLb = FindVisualChildByName<Label>(preRow, "lb");
 50                     preLb.Background = new SolidColorBrush(Colors.Transparent);
 51                     preSelIndex = selIndex;
 52
 53
 54
 55                     DataGridRow row = GetRow(dataGridTestCase, selIndex);
 56                     Label lb = FindVisualChildByName<Label>(row, "lb");
 57                     lb.Background = new SolidColorBrush(Colors.Orange);
 58                     OnPropertyChanged(nameof(SelIndex));
 59                 }
 60
 61             }
 62         }
 63         public MainWindow()
 64         {
 65             InitializeComponent();
 66             Init();
 67         }
 68         private void Init()
 69         {
 70             this.DataContext = this;
 71             CaseCollection = new ObservableCollection<Case>();
 72             CaseCollection.Add(new Case("描述1", "成功"));
 73             CaseCollection.Add(new Case("描述2", "成功"));
 74             CaseCollection.Add(new Case("描述3", "失败"));
 75             CaseCollection.Add(new Case("描述3", "失败"));
 76         }
 77         public DataGridRow GetRow(DataGrid datagrid, int columnIndex)
 78         {
 79             DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
 80             if (row == null)
 81             {
 82                 datagrid.UpdateLayout();
 83                 datagrid.ScrollIntoView(datagrid.Items[columnIndex]);
 84                 row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(columnIndex);
 85             }
 86             return row;
 87         }
 88         public T FindVisualChildByName<T>(Visual parent, string name) where T : Visual
 89         {
 90             if (parent != null)
 91             {
 92                 for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
 93                 {
 94                     var child = VisualTreeHelper.GetChild(parent, i) as Visual;
 95                     string controlName = child.GetValue(Control.NameProperty) as string;
 96                     if (controlName == name)
 97                     {
 98                         return child as T;
 99                     }
100                     else
101                     {
102                         T result = FindVisualChildByName<T>(child, name);
103                         if (result != null)
104                             return result;
105                     }
106                 }
107             }
108             return null;
109         }
110     }
111
112     public class Case
113     {
114         public string Description { get; set; }
115         public string TestResult { get; set; }
116         public Case()
117         {
118
119         }
120         public Case(string description, string testResult)
121         {
122             this.Description = description;
123             this.TestResult = testResult;
124         }
125     }
126
127     public class Text2ImageConverter : IValueConverter
128     {
129         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
130         {
131             if (value == null)
132                 return null;
133
134             string p = value.ToString();
135             if (p == "成功")
136             {
137                 if (parameter.ToString() == "1")
138                 {
139                     return new BitmapImage(new Uri("../Resource/Success.png", UriKind.RelativeOrAbsolute));
140                 }
141                 else
142                 {
143                     return new BitmapImage(new Uri("Resource/Success.png", UriKind.RelativeOrAbsolute));
144                 }
145
146             }
147             else if (p == "失败")
148             {
149                 if (parameter.ToString() == "1")
150                 {
151                     return new BitmapImage(new Uri("../Resource/Fail.png", UriKind.RelativeOrAbsolute));
152                 }
153                 else
154                 {
155                     return new BitmapImage(new Uri("Resource/Fail.png", UriKind.RelativeOrAbsolute));
156                 }
157
158             }
159             else
160             {
161                 return null;
162             }
163
164         }
165
166         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
167         {
168             return null;
169         }
170     }
171 }

原文地址:https://www.cnblogs.com/3xiaolonglong/p/12199746.html

时间: 2024-10-22 18:51:21

WPF日积月累之DataGrid样式以及操作数据模板中的控件的相关文章

在DataList、Repeater的HeaderTemplate和FooterTemplate模板中寻找控件FindControl

[程序代码] <asp:Repeater ID="Repeater1" runat="server"> <HeaderTemplate> <asp:Label ID="Label1" runat="server" Text="AAAAAAA"></asp:Label> </HeaderTemplate> <ItemTemplate> &

WPF中查找控件的扩展类

在wpf中查找控件要用到VisualTreeHelper类,但这个类并没有按照名字查找控件的方法,于是搜索网络,整理出下面这个类,感觉用起来很是方便. 贴出来,供大家参考. /// <summary> /// WPF/Silverlight 查找控件扩展方法 /// </summary> public static class VisualHelperTreeExtension { /// <summary> /// 根据控件名称,查找父控件 /// elementNa

WPF中Ribbon控件的使用

这篇博客将分享如何在WPF程序中使用Ribbon控件.Ribbon可以很大的提高软件的便捷性. 上面截图使Outlook 2010的界面,在Home标签页中,将所属的Menu都平铺的布局,非常容易的可以找到想要的Menu.在Outlook 2003时代,将Home下面的Menu都垂直的排列下来,操作的便捷程度降低了很多.Ribbon的布局会随着窗体的变化动态的调整. 上面的图片中标注了Ribbon的4个区块. 下面我们就在WPF中使用Ribbon控件来实现一个简单的界面. 1. 添加System

wpf中手风琴控件Accordion编辑模板后控件不正常。

昨天有个网友Accordion控件从sl迁移到wpf时候显示不正常.也是就没有效果. 我也是sl做的比较多,wpf玩的少,Accordion模板里触发器,状态组调了一早上都没达到满意效果, 无奈只有百度,发现了老外一个Accordion模板的例子http://blogs.u2u.be/diederik/post/2010/02/20/How-to-play-the-Accordion-WPF-Toolkit.aspx .向我项目里迁移的时候发现,居然不生效!!!! 最后一一对比发现我项目里有sy

WPF加载Winform窗体时 报错:子控件不能为顶级窗体

一.wpf项目中引用WindowsFormsIntegration和System.Windows.Forms 二.Form1.Designer.cs 的 partial class Form1 设置为:public partial class Form1 三.代码如下: XXXX.Form1 Zhuwindow = new XXXX.Form1(); Zhuwindow.TopLevel = false; Zhuwindow.FormBorderStyle = System.Windows.Fo

WPF中一个控件绑定另一个控件的属性

原文:WPF中一个控件绑定另一个控件的属性 如同一个Grid中的一个按钮根据另一个按钮的显示与否作出不同的响应: 绑定的时候通过ElementName来指定控件 <Grid Margin="50,130"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="40"/> </Grid.ColumnDefinitions>

【C#/WPF】用Thumb做可拖拽的UI控件

原文:[C#/WPF]用Thumb做可拖拽的UI控件 需求:简单的可拖拽的图片 使用System.Windows.Controls.Primitives.Thumb类 前台: <Canvas x:Name="g"> <Thumb Canvas.Left="10" Canvas.Top="20" Canvas.ZIndex="99" DragDelta="Thumb_DragDelta"&g

WPF中窗口控件的跨线程调用

原文:WPF中窗口控件的跨线程调用 在WinForm中,我们要跨线程访问窗口控件,只需要设置属性CheckForIllegalCrossThreadCalls = false;即可. 在WPF中要麻烦一下,同样的不允许跨线程访问,因为没有权限,访问了会抛异常: 没有CheckForIllegalCrossThreadCalls 属性,怎么办? 在WPF中的窗口控件都有一个Dispatcher属性,允许访问控件的线程:既然不允许直接访问,就告诉控件我们要干什么就好了. 方法如下: private

C# WPF 低仿网易云音乐(PC)歌词控件

原文:C# WPF 低仿网易云音乐(PC)歌词控件 提醒:本篇博客记录了修改的过程,废话比较多,需要项目源码和看演示效果的直接拉到文章最底部~ 网易云音乐获取歌词的api地址 http://music.163.com/api/song/media?id=歌曲ID 填写歌曲的id即可获取到json格式的数据(歌曲ID获取的方法是:点击分享按钮>其他分享>复制链接,就可以在链接中看到了): {"songStatus":0,"lyricVersion":10,