如何为DataGrid列和行自定义CellStyle

时间:2016-10-22 12:31:44

标签: .net wpf vb.net xaml datagrid

所以我有一个日历和一个按钮。选择日期并单击按钮后,程序应该从sql数据库中获取所选日期的数据。我在数据表中收集数据,我想在datagrid中显示这个数据表。这是我背后的代码:

Private Sub btnFiltro_Click(sender As Object, e As RoutedEventArgs) Handles btnFiltro.Click
    Dim dt As DataTable
    dt = b.fillDataGrid(from.SelectedDate)
    dataGrid.ItemsSource = dt.DefaultView

End Sub

Public Function fillDataGrid(ByVal Data As Date) As DataTable
    Dim dt As New DataTable()
    Dim cmd As New SqlCommand("SELECT [Statusi] FROM [Database1].[dbo].[Table1] WHERE Data = @Data", conn)
    cmd.Parameters.AddWithValue("@Data", Data)
    cmd.CommandType = CommandType.Text
    Dim adp As New SqlDataAdapter(cmd)
    adp.Fill(dt)
    Return dt
End Function

这是我在数据网格上显示数据的方式。我现在要做的是,我想将前景颜色更改为行的红色,其中“状态”列下的单元格值等于" Humbese"。我试着这样做:

<DataGrid attributes here... >
            <DataGrid.CellStyle>
                <Style TargetType="{x:Type DataGridCell}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Status}"  Value="Humbese" >
                            <Setter Property="Foreground" Value="Red" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.CellStyle>
        </DataGrid>

但只有当我手动编写&#34; Humbese&#34;在那个特定的细胞中。我想要的是,自动更改颜色,换句话说,当我点击按钮时我希望行的前景颜色已经是红色,如果它的单元格包含字符串&#34; Humbese&#34;。 你知道怎么做吗?

编辑1: 我创建了一个新项目来试用您的代码,这里是我的完整代码: XAML:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:datagridExample"
    mc:Ignorable="d"
    Title="MainWindow" Height="385.993" Width="739.716">
<Window.Resources>

    <Style x:Key="DataGridCellStyle1" TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status}"  Value="Humbese" >
                <Setter Property="Background" Value="Red" />
                <Setter Property="Foreground" Value="White" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>

<Grid>

    <!--
<DataGrid ItemsSource="{Binding Data}" 
          CellStyle="{StaticResource DataGridCellStyle1}" />

-->

    <DataGrid x:Name="dg" ItemsSource="{Binding Data}" 
          AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Ora}"
                            Width="*"
                            Header="Date"/>
            <DataGridTextColumn Binding="{Binding Status}" 
                            CellStyle="{StaticResource DataGridCellStyle1}"
                            Width="*"
                            Header="Status" />
        </DataGrid.Columns>
    </DataGrid>


    <Button VerticalAlignment="Bottom" Click="Button_Click">LOAD</Button>
    <Calendar x:Name="from" HorizontalAlignment="Left" Margin="253,91,0,0" VerticalAlignment="Top"/>

</Grid>

MainWindow.xaml.vb:

Class MainWindow

Dim vm As Class1
Sub New()


    InitializeComponent()
    vm = New Class1()

    DataContext = vm

End Sub

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    vm.LoadData(from.SelectedDate())
End Sub
End Class

Class1.vb(你的viewmodel类):

Public Class Class1
Public Property Data() As MyDataTable
    Get
        Return m_Data
    End Get
    Set
        m_Data = Value
    End Set
End Property
Private m_Data As MyDataTable

Public Sub New()
    Data = New MyDataTable()
End Sub

Public Sub LoadData(dataaa As Date)
    Data.loadData(dataaa)
End Sub
End Class

MyDataTable.vb:

Imports System.Data.SqlClient
Imports System.Data

Public Class MyDataTable
Inherits DataTable
Dim conn As SqlConnection
Dim stringBuilder As SqlConnectionStringBuilder
Dim statusi As Integer()

Sub New()
    connectTo()
    Columns.Add("Date", GetType(DateTime))
    Columns.Add("Statusi", GetType(String))
End Sub

Public Sub connectTo()
    stringBuilder = New SqlConnectionStringBuilder()
    stringBuilder.DataSource = "DESKTOP-CPTM4LG\SQLEXPRESS"
    stringBuilder.InitialCatalog = "database1"
    stringBuilder.IntegratedSecurity = True

    conn = New SqlConnection(stringBuilder.ToString())
End Sub

Public Sub loadData(data As Date)
    Dim cmd As New SqlCommand("SELECT [Ora], [Status] FROM [database1].[dbo].[table1] WHERE Data = @Data", conn)
    cmd.Parameters.AddWithValue("@Data", data)
    cmd.CommandType = CommandType.Text
    Dim adp As New SqlDataAdapter(cmd)
    adp.Fill(Me)


End Sub

结束班

1 个答案:

答案 0 :(得分:1)

要更改特定列的单元格样式,请将样式应用于该特定列:

    <DataGrid ItemsSource="{Binding Data}" 
              AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Date}"
                                Width="*"
                                Header="Date"/>
            <DataGridTextColumn Binding="{Binding Status}" 
                                CellStyle="{StaticResource DataGridCellStyle1}"
                                Width="*"
                                Header="Status" />
        </DataGrid.Columns>
    </DataGrid>

enter image description here

要更改特定行中所有列的单元格样式,请将样式应用于DataGrid

    <DataGrid ItemsSource="{Binding Data}" 
              CellStyle="{StaticResource DataGridCellStyle1}" />

enter image description here

<强>样式:

    <Style x:Key="DataGridCellStyle1" TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status}"  Value="Humbese" >
                <Setter Property="Background" Value="Red" />
                <Setter Property="Foreground" Value="White" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

编辑:添加完整代码:

<强> XAML:

<Window x:Class="WpfApplication313.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication313"
    mc:Ignorable="d"
    Title="MainWindow" 
    Height="300" 
    Width="300">
<Window.Resources>

    <Style x:Key="DataGridCellStyle1" TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding Status}"  Value="Humbese" >
                <Setter Property="Background" Value="Red" />
                <Setter Property="Foreground" Value="White" />
                <Setter Property="FontWeight" Value="Bold" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

</Window.Resources>

<Grid>

    <!--
    <DataGrid ItemsSource="{Binding Data}" 
              CellStyle="{StaticResource DataGridCellStyle1}" />

    -->

    <DataGrid ItemsSource="{Binding Data}" 
              AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Date}"
                                Width="*"
                                Header="Date"/>
            <DataGridTextColumn Binding="{Binding Status}" 
                                CellStyle="{StaticResource DataGridCellStyle1}"
                                Width="*"
                                Header="Status" />
        </DataGrid.Columns>
    </DataGrid>


    <Button VerticalAlignment="Bottom" Click="Button_Click">LOAD</Button>

</Grid>

<强>代码隐藏:

public partial class MainWindow : Window
{
    MyViewModel vm;

    public MainWindow()
    {
        InitializeComponent();

        vm = new MyViewModel();
        DataContext = vm;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        vm.LoadData();
    }
}

<强>视图模型:

public class MyViewModel
{
    public MyDataTable Data { get; set; }

    public MyViewModel()
    {
        Data = new MyDataTable();
    }

    public void LoadData()
    {
        // loading data from DB here
        Data.LoadData();
    }
}

编辑2:这不重要,但添加代码以填充DataTable,以使其更加清晰。

public class MyDataTable : DataTable
{
    public MyDataTable()
    {
        Columns.Add("Date", typeof(DateTime));
        Columns.Add("Status", typeof(string));
    }

    public void LoadData()
    {
        // for simplicity, please assume data loaded from DB here

        for (int i = 1; i <= 10; i++)
        {
            DataRow dr = NewRow();
            dr["Date"] = DateTime.Now.AddDays(-i).Date;
            dr["Status"] = string.Format("Status {0}", i);
            Rows.Add(dr);
        }

        Rows[2]["Status"] = "Humbese";
        Rows[4]["Status"] = "Humbese";
        Rows[7]["Status"] = "Humbese";
    }
}

编辑3:您的代码问题是列名称不一致:DataTable将其声明为Statusi,绑定使用Status。修好后,你的代码工作了:

enter image description here