动态地将行颜色分配给SQL数据库中的ListView WPF

时间:2015-07-20 21:55:14

标签: c# css wpf listview

我是WPF新手并且无法使用数据绑定模板。我已经搜索了几个小时,并努力找到一种方法来完成这项工作。

我有一个从sql server填充的listview。在列表视图中,我希望行更改颜色以匹配其适当的状态。我想避免为Lead Class分配颜色,所以我需要从SQL表中提取颜色并动态设置它们。下面的代码使用单击按钮,可能会作为一种方法,但显然这不是" WPF方式"。我怎样才能做到这一点"纠正"方式是什么?

注意:每个状态及其各自的颜色将始终不同。

private void addLeadButton_Click(object sender, RoutedEventArgs e)
{
    DataTable sqlColorList = SqlLoader.selectFromSqlDatabase("Select * FROM statusTable");

    int i = 0;
    foreach (Lead test in LeadListView.Items)
    {
        foreach (DataRow color in sqlColorList.Rows)
        {
            if (test.LeadStatus == color["status"].ToString())
            {
                ListViewItem row = LeadListView.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
                row.Background = (Brush)new System.Windows.Media.BrushConverter().ConvertFromString(color["color"].ToString());
            }
        }
        i++;
    }
}


<ListView x:Name="LeadListView" Width="494" Margin="10,127,0,34"     HorizontalAlignment="Left">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Foreground" Value="Black" />
            <Setter Property="BorderBrush" Value="LightGray" />
            <Setter Property="BorderThickness" Value="0,0,0,1" />
        </Style>
    </ListView.ItemContainerStyle>

    <ListView.View>
        <GridView>
            <GridViewColumn Header="First Name" Width="121" DisplayMemberBinding="{Binding LeadFirstName}"/>
            <GridViewColumn Header="Last Name" Width="121" DisplayMemberBinding="{Binding LeadLastName}"/>
            <GridViewColumn Header="Status" Width="121" DisplayMemberBinding="{Binding LeadStatus}"/>
            <GridViewColumn Header="Date" Width="121" DisplayMemberBinding="{Binding LeadDate, StringFormat='MM/dd/yyyy'}"/>
        </GridView>
    </ListView.View>
</ListView>

1 个答案:

答案 0 :(得分:1)

你不应该在代码中这样做。在您的XAML中,只需将Background属性绑定到LeadStatus属性,并指定一个值转换器,将其从LeadStatus转换为Brush。