namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel
{
public ObservableCollection<Employee> Employees { get; set; }
public ViewModel()
{
Employees = new ObservableCollection<Employee>()
{
new Employee() { Name="John Doe", Age=30, Salary=5000 },
new Employee() { Name="Jane Smith", Age=25, Salary=4000 },
new Employee() { Name="Tom Brown", Age=35, Salary=6000 }
};
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
}
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
MergeCells();
}
private void MergeCells()
{
// 第一列合并单元格
var cells = GetCells(0);
for (int i = 0; i < cells.Count; i++)
{
if (i > 0 && cells[i].Content.ToString() == cells[i - 1].Content.ToString())
{
cells[i].Visibility = Visibility.Collapsed;
cells[i - 1].RowSpan++;
}
}
}
private List<DataGridCell> GetCells(int column)
{
var cells = new List<DataGridCell>();
for (int i = 0; i < dataGrid.Items.Count; i++)
{
var row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
var cell = (DataGridCell)dataGrid.Columns[column].GetCellContent(row).Parent;
cells.Add(cell);
}
return cells;
}
}
public class ViewModel
{
public ObservableCollection<Employee> Employees { get; set; }
public ViewModel()
{
Employees = new ObservableCollection<Employee>()
{
new Employee() { Name="John Doe", Age=30, Salary=5000 },
new Employee() { Name="Jane Smith", Age=25, Salary=4000 },
new Employee() { Name="Tom Brown", Age=35, Salary=6000 },
new Employee() { Name="Tom Brown", Age=50, Salary=8000 }
};
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
}
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel
{
public ObservableCollection<Employee> Employees { get; set; }
public ViewModel()
{
Employees = new ObservableCollection<Employee>()
{
new Employee() { Name="John Doe", Age=30, Salary=5000 },
new Employee() { Name="Jane Smith", Age=25, Salary=4000 },
new Employee() { Name="Tom Brown", Age=35, Salary=6000 }
};
}
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
}
}