wpf-datagrid

注意加载数据需要在 Loaded 事件里面。因为表格还没加载完毕时是无法显示数据的。

更新完 dg.ItemsSource 对应的 List 之后,表格会自动更新,增加和删除都可以

自动生成

根据数据源字段自动生成列

<Grid Margin="10">
<DataGrid Name="dgSimple"></DataGrid>
</Grid>

List<User> users = new List<User>();
users.Add(new User() { dbId=11, Id = 1, Name = "John Doe", Birthday = new DateTime(1971, 7, 23) });
users.Add(new User() { dbId = 12, Id = 2, Name = "Jane Doe", Birthday = new DateTime(1974, 1, 17) });
users.Add(new User() { dbId = 13, Id = 3, Name = "Sammy Doe", Birthday = new DateTime(1991, 9, 2) });

dgSimple.ItemsSource = users;

public class User
{
public int dbId { get; set; }
public int Id { get; set; }

public string Name { get; set; }

public DateTime Birthday { get; set; }
}

删除一行

private void btn_delete_rows_Click(object sender, RoutedEventArgs e)
{
int count = dg.SelectedItems.Count;
for (int i = 0; i < count; i++)
{
// 这里 SelectedItems 的索引会有变化。所以只要计数每次删除第 0 个就可以了
var item = dg.SelectedItems[0] as Model_prog_coeff;
App.db.Delete_model<Model_prog_coeff>(item, item.ID);
for (var j = 0; j < App.db.m_coeffs.Count; ++j)
{
if (App.db.m_coeffs[j].ID == item.ID)
{
App.db.m_coeffs.RemoveAt(j);
}
}
}
}

右键菜单

<DataGrid>
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="Click Me" Click="MenuItem_Click" />
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>

选择设置

DataGrid 的选择单位有3种,整行、单个 Cell 、单个 Cell 和 点行头选择整行。DataGrid 缺省状态是整行

private void cbbSelectMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
dtgShow.SelectionUnit = (DataGridSelectionUnit)cbbSelectMode.SelectedValue;
}

<ComboBox Name="cbbSelectMode" Margin="2" SelectionChanged="cbbSelectMode_SelectionChanged"/>

// 禁止选择多行
SelectionMode="Single"

只读

xaml 里面 Mode=OneWay 就可以了

禁止双击编辑行为:IsReadOnly=”True”

选择当前行

var item = dg.SelectedItem as Model_sensor;
if ((null != item) && (item.driver != "" && item.driver != null) &&
(item.name != "" && item.name != null))
{
if (item.ID == 0)
{
App.db.Insert_model<Model_sensor>(item);
}
else
{
App.db.Update_model<Model_sensor>(item);
}
}

选择行事件

<DataGrid Name="dgScreenRecords" DockPanel.Dock="Left" Width="300" AutoGenerateColumns="False" 
SelectionChanged="dgScreenRecords_SelectionChanged"
IsReadOnly="True" CanUserSortColumns="True" LoadingRow="dg_LoadingRow" CanUserAddRows="False">
private void dgScreenRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(dataGrid.SelectedIndex);
var sr = (Model_Screen_record)row.Item;

}

根据单元格信息设置行颜色

<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="#95F68D0E"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>

列控件

DataGridTextColumn
DataGridCheckBoxColumn
DataGridComboBoxColumn
DataGridHyperlinkColumn
DataGridTemplateColumn:允许你定义任意类型的内容

样例

<Grid x:Name="grid_main">
<DataGrid Name="dg" AutoGenerateColumns="False" CanUserSortColumns="True" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding UserName, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="学生姓名"/>
<DataGridTextColumn Binding="{Binding ClassName, UpdateSourceTrigger=PropertyChanged}" Width="100" Header="班级名称"/>
<DataGridTextColumn Binding="{Binding Address, UpdateSourceTrigger=PropertyChanged}" Width="200" Header="地址"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Left">
<Button Content="编辑" Click="Button_edit"/>
<Button Margin="8 0 0 0" Content="删除" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>

public MainWindow()
{
InitializeComponent();

List<Student> students = new List<Student>();
students.Add(new Student() { UserName = "小王", ClassName = "高二三班", Address = "广州市" });
students.Add(new Student() { UserName = "小李", ClassName = "高三六班", Address = "清远市" });
students.Add(new Student() { UserName = "小张", ClassName = "高一一班", Address = "深圳市" });
students.Add(new Student() { UserName = "小黑", ClassName = "高一三班", Address = "赣州市" });
dg.ItemsSource = students;
...
}

public class Student
{
public string UserName { get; set; }
public string ClassName { get; set; }
public string Address { get; set; }
}

splitter

<Window x:Class="WpfTutorialSamples.Panels.GridSplitterSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="GridSplitterSample" Height="300" Width="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock FontSize="55" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap">Left side</TextBlock>
<GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" />
<TextBlock Grid.Column="2" FontSize="55" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap">Right side</TextBlock>
</Grid>
</Window>

事件

xaml 里面添加属性
项目|说明
–|–
RowEditEnding=”dg_RowEditEnding” | 结束行编辑
CellEditEnding=”dg_CellEditEnding” |结束单元格编辑
LoadingRow=”dg_LoadingRow”| 载入行数据
SelectionChanged| 选中行

自动添加序号

// xaml 添加属性
LoadingRow="dg_LoadingRow"

private void dtgShow_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
}

对齐行号

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" LoadingRow="OnLoadingRow">
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
</DataGrid.Columns>
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<Label HorizontalAlignment="Center"
Content="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow},
Path=Header}"/>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
</DataGrid>

默认选中行

<DataGrid Name="dg" Grid.Row="1" AutoGenerateColumns="False" CanUserSortColumns="True" 
SelectionUnit="FullRow" AlternationCount="2" CanUserAddRows="False"
LoadingRow="dg_LoadingRow" RowEditEnding="dg_RowEditEnding" Loaded="dg_Loaded"
AlternatingRowBackground="#99CCFF">
private void dg_Loaded(object sender, RoutedEventArgs e)
{
dg.SelectedIndex = 0;
dg.Focus();
}

保持高亮

<DataGrid.Resources>
<Style TargetType="DataGridRow">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="#4C7899"/>
</Style.Resources>
</Style>
</DataGrid.Resources>

// 代码实现
dg.RowStyle = new Style();
dg.RowStyle.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, new SolidColorBrush(Color.FromArgb(0xff,0x33,0x99,0xff)));
dg.RowStyle.Resources.Add(SystemColors.InactiveSelectionHighlightTextBrushKey, new SolidColorBrush(System.Windows.Media.Colors.White));

获取选择行

var item = dg.SelectedItem as Model_master;
if (item == null)
{
dg_attr.ItemsSource = null;
dg_preelaboration.ItemsSource = null;
return;
}
int count = dg.SelectedItems.Count;
for (int i = 0; i < count; i++)
{
var item = dg.SelectedItems[i] as Model_coeff;
if (item == null) continue;
App.db.Delete_model<Model_coeff>(item, item.ID);
}

保存数据到数据库

// 绑定数据时,UpdateSourceTrigger 指定这个,然后在 RowEditEnding 回调中拿到修改后的数据。
<DataGridTextColumn Header="ID" Binding="{Binding EmpNo, UpdateSourceTrigger=PropertyChanged}"/>

// use code implement
private void load_coeff()
{
dg.Columns.Clear();//每次清空列集合
List<Tuple<string, string>> col_list = new List<Tuple<string, string>>();
col_list.Add(Tuple.Create("序号", "no"));
col_list.Add(Tuple.Create("名称", "name"));
col_list.Add(Tuple.Create("说明", "comment"));
col_list.Add(Tuple.Create("数值", "value"));

foreach (var col in col_list)
{
DataGridTextColumn textBoxColumn = new DataGridTextColumn();
textBoxColumn.Header = col.Item1;


//定义每一列的宽度相同
textBoxColumn.Width = new DataGridLength(dg.ActualWidth, DataGridLengthUnitType.Star);
textBoxColumn.MinWidth = 50; //定义每一列的最小宽度

Binding binding = new Binding();//设置每一列的binding
binding.Path = new PropertyPath(col.Item2);
if (col.Item2 == "no")
{
binding.Mode = BindingMode.OneWay;
}else
{
binding.Mode = BindingMode.TwoWay;
}
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
textBoxColumn.Binding = binding;

dg.Columns.Add(textBoxColumn);//将列添加到集合中
}
dg.ItemsSource = null;
dg.ItemsSource = m_db.list_coeff();
}

根据列宽调整大小

private void Load_sensor()
{
dg.Columns.Clear();//每次清空列集合
List<Tuple<string, string>> col_list = new List<Tuple<string, string>>();
col_list.Add(Tuple.Create("名称", "name"));
col_list.Add(Tuple.Create("说明", "comment"));

foreach (var col in col_list)
{
DataGridTextColumn dgColumn = new DataGridTextColumn();
dgColumn.Header = col.Item1;

//定义每一列的宽度相同
if(col.Item1 == "说明" || col.Item1 == "名称")
{
dgColumn.Width = new DataGridLength(dg.ActualWidth, DataGridLengthUnitType.SizeToCells);
}
else
{
dgColumn.Width = new DataGridLength(dg.ActualWidth, DataGridLengthUnitType.Star);
}
dgColumn.MinWidth = 50; //定义每一列的最小宽度

Binding binding = new Binding();//设置每一列的binding
binding.Path = new PropertyPath(col.Item2);
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
dgColumn.Binding = binding;

dg.Columns.Add(dgColumn);//将列添加到集合中
}
dg.ItemsSource = null;
dg.ItemsSource = m_db.List_sensor();
}

添加 combobox

TechNet

添加动态数据。

<Application x:Class="wpf_ComboBoxColumn.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:wpf_ComboBoxColumn"
StartupUri="MainWindow.xaml">
<Application.Resources>
<local:ColourCollection x:Key="ColourSource">
<!--<local:SimpleColour ColourString="Yellow" Id="1"/>
<local:SimpleColour ColourString="Blue" Id="2"/>
<local:SimpleColour ColourString="Red" Id="3"/>
<local:SimpleColour ColourString="Green" Id="4"/>
<local:SimpleColour ColourString="Purple" Id="5"/>-->
</local:ColourCollection>
</Application.Resources>
</Application>

public class Model_drivers
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string name { get; set; }
}

//ColourCollection.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace wpf_ComboBoxColumn
{
public class ColourCollection : ObservableCollection<SimpleColour>
{
}
}

//SimpleColour.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace wpf_ComboBoxColumn
{
public class SimpleColour
{
public int ID { get; set; }
public string ColourString { get; set; }

}
}

<DataGrid ItemsSource="{Binding Medias}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Type" Binding="{Binding MediaType}" />
<DataGridTextColumn Header="Container" Binding="{Binding Container}" />
<DataGridTextColumn Header="Volume" Binding="{Binding Volume}" />
<DataGridComboBoxColumn
Header="ComboboxColumn"
ItemsSource="{DynamicResource ColourSource}"
SelectedValueBinding="{Binding ColourId, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="ID"
DisplayMemberPath="ColourString"
>
</DataGridComboBoxColumn>
<DataGridTemplateColumn Header="TemplateColumn">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.Colours, RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
SelectedValuePath="MColour.Id"
SelectedValue="{Binding ColourId, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<Rectangle Fill="{Binding ColourBrush}" Height="30" Width="30"/>
</DataTemplate>
</ComboBox.ItemTemplate>

</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

Template 添加数据

<DataGridTemplateColumn Header="驱动">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.collectionDriver, RelativeSource={RelativeSource AncestorType=local:UCSensor}}"
IsEditable="True"
SelectedValue="{Binding DriverID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="DriverID" DisplayMemberPath="Name"
SelectionChanged="ComboBox_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

public class Model_driver
{
[PrimaryKey, AutoIncrement]
public int DriverID { get; set; }
public string DriverName { get; set; }
public string Version { get; set; }
public string Comment { get; set; }
// 是否启用
public bool IsEnable { get; set; }
}

public class NotifyUIBase : INotifyPropertyChanged
{
// Very minimal implementation of INotifyPropertyChanged matching msdn
// Note that this is dependent on .net 4.5+ because of CallerMemberName
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class UCMeasureStepViewModel : NotifyUIBase
{
public ObservableCollection<Model_driver> collectionDriver { get; set; }

public UCMeasureStepViewModel()
{
collectionDriver = new ObservableCollection<Model_driver>();

if (App.db.m_drivers.Count == 0)
{
App.db.List_driver();
}
foreach (var item in App.db.m_drivers)
{
collectionDriver.Add(item);
}

RaisePropertyChanged("collectionDriver");
}

}

多行编辑

<DataGridTextColumn Binding="{Binding Formular, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MinWidth="200"  Width="Auto" Header="公式">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.EditingElementStyle>
<Style TargetType="TextBox">
<Setter Property="TextWrapping" Value="Wrap" />
<Setter Property="AcceptsReturn" Value="true" />
</Style>
</DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

输入小数点


添加 checkbox

// xaml
<DataGrid Name="dg" Grid.Row="1" AutoGenerateColumns="False" CanUserSortColumns="True"
SelectionUnit="FullRow" AlternationCount="2" CanUserAddRows="True"
LoadingRow="dg_LoadingRow" RowEditEnding="dg_RowEditEnding">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding name}" Width="Auto" Header="名称"/>
<DataGridTextColumn Binding="{Binding comment}" Width="Auto" Header="说明"/>
<DataGridTextColumn Binding="{Binding driver}" Width="Auto" Header="驱动"/>
<DataGridTemplateColumn Header="启用" Width="40">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chk_isEnable" IsChecked="{Binding isEnable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Click="chk_isEnable_Click"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding channel}" Width="Auto" Header="通道"/>
<DataGridTextColumn Binding="{Binding lower}" Width="Auto" Header="下限"/>
<DataGridTextColumn Binding="{Binding upper}" Width="Auto" Header="上限"/>
<DataGridTextColumn Binding="{Binding test_type}" Width="Auto" Header="测试类型"/>
<DataGridTextColumn Binding="{Binding gain}" Width="Auto" Header="增益"/>
<DataGridTextColumn Binding="{Binding offset}" Width="Auto" Header="偏置"/>
<DataGridTextColumn Binding="{Binding direction}" Width="Auto" Header="方向"/>
<DataGridTextColumn Binding="{Binding precision}" Width="Auto" Header="显示精度"/>
</DataGrid.Columns>
</DataGrid>



// code
private void chk_isEnable_Click(object sender, RoutedEventArgs e)
{
// 获取当前选中行,更新
var result = (sender as CheckBox).IsChecked;
var item = dg.SelectedItem as Model_sensor;
if ((item.driver != "" && item.driver != null) &&
item.name != "" && item.name != null)
{
if (item.ID == 0)
{
App.db.Insert_model<Model_sensor>(item);
}
else
{
App.db.Update_model<Model_sensor>(item);
}
}
}

添加 checkbox 全选框

<DataGrid Name="dg" Grid.Row="2" AutoGenerateColumns="False" CanUserSortColumns="True" 
SelectionUnit="FullRow" AlternationCount="2" CanUserAddRows="False"
LoadingRow="dg_LoadingRow"
AlternatingRowBackground="#99CCFF" >
<DataGrid.Columns>
<DataGridTemplateColumn Width="60">
<DataGridTemplateColumn.Header>
<CheckBox x:Name="chk_header_upload" Checked="chk_header_upload_Checked" Unchecked="chk_header_upload_Unchecked">上传</CheckBox>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chk_isUpload" IsChecked="{Binding isUpload, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding DateTime, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="Auto" Header="日期时间"/>
<DataGridTextColumn Binding="{Binding Batch, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="Auto" Header="批次"/>
<DataGridTextColumn Binding="{Binding MeasureInfo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="Auto" Header="测量项"/>
</DataGrid.Columns>
</DataGrid>

private void chk_header_upload_Checked(object sender, RoutedEventArgs e)
{
foreach(var it in App.db.m_manualUpload)
{
it.isUpload = true;
}
dg.ItemsSource = null;
dg.ItemsSource = App.db.m_manualUpload;
}

private void chk_header_upload_Unchecked(object sender, RoutedEventArgs e)
{
foreach (var it in App.db.m_manualUpload)
{
it.isUpload = false;
}
dg.ItemsSource = null;
dg.ItemsSource = App.db.m_manualUpload;
}

‘DeferRefresh’ is not allowed during an AddNew or EditItem transaction

解决方法如下

void DataGrid_Unloaded(object sender, RoutedEventArgs e)
{
var grid = (DataGrid)sender;
grid.CommitEdit(DataGridEditingUnit.Row, true);
}

查找控件

<DataGrid x:Name="dg" Grid.Row="1" AutoGenerateColumns="False" CanUserSortColumns="True" 
SelectionUnit="FullRow" AlternationCount="2" CanUserAddRows="False"
LoadingRow="dg_LoadingRow" RowEditEnding="dg_RowEditEnding"
AlternatingRowBackground="#99CCFF" Loaded="dg_Loaded">
<DataGrid.Columns>
<DataGridTemplateColumn Header="显示精度">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.collectionSensorPrecise, RelativeSource={RelativeSource AncestorType=local:UCSensor}}"
SelectedValue="{Binding Precision, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
IsEditable="True" DropDownOpened="cmb_driver_DropDownOpened" x:Name="cmb_precision"
SelectionChanged="ComboBox_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
foreach (var it in dg.Items)
{
DataGridTemplateColumn tempColumn1 = dg.Columns[11] as DataGridTemplateColumn;
FrameworkElement element1 = tempColumn1.GetCellContent(it);
if (element1 == null)
{
continue;
}
ComboBox comboBox1 = tempColumn1.CellTemplate.FindName("cmb_precision", element1) as ComboBox;
comboBox1.IsEditable = true;
}
// 能用
public static void FindChildGroup<T>(DependencyObject parent, string childName, ref List<T> list) where T : DependencyObject
{
// Checks should be made, but preferably one time before calling.
// And here it is assumed that the programmer has taken into
// account all of these conditions and checks are not needed.
//if ((parent == null) || (childName == null) || (<Type T is not inheritable from FrameworkElement>))
//{
// return;
//}

int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

for (int i = 0; i < childrenCount; i++)
{
// Get the child
var child = VisualTreeHelper.GetChild(parent, i);

// Compare on conformity the type
T child_Test = child as T;

// Not compare - go next
if (child_Test == null)
{
// Go the deep
FindChildGroup<T>(child, childName, ref list);
}
else
{
// If match, then check the name of the item
FrameworkElement child_Element = child_Test as FrameworkElement;

list.Add(child_Test);

// if (child_Element.Name == childName)
// {
// // Found
// list.Add(child_Test);
// // 只找一个
// return;
// }

// We are looking for further, perhaps there are
// children with the same name
FindChildGroup<T>(child, childName, ref list);
}
}

return;
}

combobox 禁止下拉框

<DataGridTemplateColumn Header="驱动">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox x:Name="cmb_driver" ItemsSource="{Binding DataContext.collectionDriver, RelativeSource={RelativeSource AncestorType=local:UCSensor}}"
SelectedValue="{Binding DriverID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="DriverID" DisplayMemberPath="Name" DropDownOpened="cmb_driver_DropDownOpened"
SelectionChanged="ComboBox_SelectionChanged" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

private void cmb_driver_DropDownOpened(object sender, EventArgs e)
{
// 未登录不允许修改
var mainwin = (MRLGauger.MainWindow)Application.Current.MainWindow;
if (MainWindow.FLAG_USER_ADMIN != (mainwin.flag&MainWindow.FLAG_USER_ADMIN))
{
ComboBox cb = sender as ComboBox;
cb.IsDropDownOpen = false;
if (cb.Name == "cmb_precision")
{
cb.IsEditable = false;
}
}else
{
ComboBox cb = sender as ComboBox;
cb.IsDropDownOpen = true;
if (cb.Name == "cmb_precision")
{
cb.IsEditable = true;
}
}
}

checkbox 只读

var mainwin = (MRLGauger.MainWindow)Application.Current.MainWindow;
if (MainWindow.FLAG_USER_ADMIN != (mainwin.flag&MainWindow.FLAG_USER_ADMIN))
{
var chk = sender as CheckBox;
if ((bool)chk.IsChecked)
{
(sender as CheckBox).IsChecked = false;
}
else
{
(sender as CheckBox).IsChecked = true;
}
e.Handled = true;
return;
}else
{
// 获取当前选中行,更新
var result = (sender as CheckBox).IsChecked;
var item = dg.SelectedItem as Model_sensor;
if ((null != item) && (item.DriverID != 0) &&
(item.Name != "" && item.Name != null))
{
if (item.ID == 0)
{
App.db.Insert_model<Model_sensor>(item);
}
else
{
App.db.Update_model<Model_sensor>(item);
}
}
else
{
MessageBox.Show("驱动和名称为必要参数");
}
}

不显示滚动条问题

StackPanel 会导致滚动条不显示,改用 DockPanel
显示水平滚动条,不能用 * 可以用 auto

<DockPanel Grid.Row="3">
<Button x:Name="btn_delete_all" Click="btn_delete_all_Click" DockPanel.Dock="Top">清空日志</Button>
<DataGrid Name="dgLog" DockPanel.Dock="Top" AutoGenerateColumns="False" CanUserSortColumns="True" IsReadOnly="True" VerticalScrollBarVisibility="Auto"
SelectionUnit="FullRow" AlternationCount="2" CanUserAddRows="False" >
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding Type}" Value="警告">
<Setter Property="Background" Value="Orange"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding Type}" Value="错误">
<Setter Property="Background" Value="orangered" ></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Time, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="120" Header="时间"/>
<DataGridTextColumn Binding="{Binding Type, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="40" Header="类型"/>
<DataGridTextColumn Binding="{Binding Info, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="auto" Header="信息"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>