着色Wpf DataGrid单元格边框

时间:2018-10-04 08:04:30

标签: c# wpf vb.net

xaml

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button x:Name="Button1" Height="25" Width="100" Content="Fill Data" VerticalAlignment="Top" />
    <Button x:Name="Button2" Height="25" Width="100" Content="Color Border" VerticalAlignment="Top" Margin="0,30,0,0"/>
    <DataGrid x:Name="DataGrid1" Width="500" Height="100" SelectionMode="Single" SelectionUnit="Cell"/>
</Grid>
</Window>

vb.net

Class MainWindow

Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
    Dim DataSet1 As System.Data.DataSet = New System.Data.DataSet
    Dim DataTable1 As System.Data.DataTable = New System.Data.DataTable
    DataTable1.Columns.Add("Name")
    DataTable1.Columns.Add("Sur Name")
    DataTable1.Columns.Add("Country")
    DataTable1.Columns.Add("Gender")
    DataTable1.Rows.Add({"Donald", "Trump", "United States", "Male"})
    DataTable1.Rows.Add({"Angela", "Merkel", "Germany", "Female"})
    DataTable1.Rows.Add({"Theresa", "May", "England", "Female"})
    DataTable1.Rows.Add({"Emmanuel", "Macron", "France", "Male"})
    DataTable1.Rows.Add({"Vladimir", "Putin", "Russia", "Male"})
    DataTable1.Rows.Add({"Recep Tayyip", "Erdogan", "Turkey", "Male"})
    DataTable1.Rows.Add({"Justin", "Trudeau", "Canada", "Male"})
    DataTable1.Rows.Add({"Xi", "Jinping", "China", "Male"})
    DataTable1.Rows.Add({"Mahmoud", "Abbas", "Palestine", "Male"})
    DataTable1.Rows.Add({"Moon", "Jae-in", "South Korea", "Male"})
    DataTable1.Rows.Add({"Shinzō", "Abe", "Japan", "Male"})
    DataTable1.Rows.Add({"Nicolas", "Maduro", "Venezuela", "Male"})
    DataTable1.Rows.Add({"Sergio", "Mattarella", "Italy", "Male"})
    DataTable1.Rows.Add({"Kim", "Jong-un", "North Korea", "Male"})
    DataSet1.Tables.Add(DataTable1)
    DataGrid1.ItemsSource = DataSet1.Tables(0).DefaultView
End Sub

Private Sub Button2_Click(sender As Object, e As RoutedEventArgs) Handles Button2.Click
    Dim myDataGridRow As DataGridRow = CType(DataGrid1.ItemContainerGenerator.ContainerFromItem(DataGrid1.Items(1)), DataGridRow)
    Dim myDataGridCell As DataGridCell = CType(DataGrid1.Columns(2).GetCellContent(myDataGridRow).Parent, DataGridCell)
    myDataGridCell.BorderBrush = New SolidColorBrush(CType(ColorConverter.ConvertFromString("#ff0000"), Color))
End Sub

End Class

请运行上面的代码,然后单击Button1和Button2。

在DataGrid上向下滚动,查看德国,中国和朝鲜的边界颜色为红色。

通常只有德国边界必须是红色的。

那么,为什么三个单元格边框是红色而不是一个?

注意: :我需要解决方案背后的代码,而不是xaml解决方案。

0 个答案:

没有答案