更改<type>列表框backcolor </type>

时间:2014-04-15 14:59:38

标签: c# wpf listbox

我有一个包含customer类型列表的Listbox。所以我的Listbox.Items不再是ListItem类型,它是customer类型。

我在客户领域有一个isActive标志,如果isActive为真,我想知道如何将背面颜色设置为红色。

目前我已经尝试了这个但是它不起作用,因为我无法将Customer转换为ListBoxtem

            List<object> inactiveCustomers = new List<object>();
        foreach (Customer item in ListBoxCustomers.Items)
        {
            if (!item.IsActive)
            {
                inactiveCustomers.Add(item);
                int index = ListBoxCustomers.Items.IndexOf(item);
                ListBoxItem x = (ListBoxItem)ListBoxCustomers.Items[index];
                x.Background = Brushes.Red;
            }
        }

编辑: 每当我取消选择一个适用于活跃客户的复选框时,我正在调用一个执行上述代码的方法。每当我取消选择Active Checkbox时,我会遍历客户并显示所有客户,此时,我想更改非活动的背景颜色,以区分哪些是不活跃的

2 个答案:

答案 0 :(得分:3)

有两种方法可以做到这一点。 “正确的”WPF方式是在XAML中完成所有操作:

<ListBox x:Name="ListBoxCustomers" ItemsSource="{Binding Customers}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsActive}" Value="False">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

在代码隐藏中执行此操作的WinForms风格方法需要从列表框中获取容器。但是,由于UI虚拟化,并非所有必需的项目都有容器。因此,此代码仅更改当前可见项的容器。如果滚动ListBox,新项目可能会或可能没有您期望的设置(取决于回收规则)。

List<object> inactiveCustomers = new List<object>();
foreach (Customer item in ListBoxCustomers.Items)
{
    if (!item.IsActive)
    {
        inactiveCustomers.Add(item);
        var container =  ListBoxCustomers.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
        if (container != null)
            container.Background = Brushes.Red;
    }
}

答案 1 :(得分:0)

要获得ListBoxItem,您可以使用ListBox&#39; s ItemContainerGenerator。确保在加载完成后执行此操作,例如在Loaded事件处理程序中,因为控件在加载之前尚不存在。

void Window_Loaded(object sender, RoutedEventArgs e)
{
    List<object> inactiveCustomers = new List<object>();
    foreach (Customer item in ListBoxCustomers.Items)
    {
        if (!item.IsActive)
        {
            inactiveCustomers.Add(item);
            ListBoxItem x = ListBoxCustomers.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
            if (x != null)
                x.Background = Brushes.Red;
        }
    }
}
相关问题