首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改<Type>列表框的背景色

更改<Type>列表框的背景色
EN

Stack Overflow用户
提问于 2014-04-15 14:59:38
回答 2查看 66关注 0票数 1

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

我在customer字段中有一个isActive标志,我想知道如果isActive是真的话,我将如何将背景色设置为红色。

目前我已经尝试过了,但是它不能工作,因为我不能让客户输入ListBoxtem

代码语言:javascript
复制
            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;
            }
        }

编辑:每当我取消选中一个针对活动客户的复选框时,我都会调用一个执行上述代码的方法。每当取消选中活动复选框时,我都会遍历客户并显示所有客户,此时,我希望更改非活动复选框的背颜色,以区分哪些是非活动/活动的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-04-15 15:15:49

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

代码语言:javascript
复制
<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,则新项目可能有或可能没有您期望的设置(取决于回收规则)。

代码语言:javascript
复制
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;
    }
}
票数 3
EN

Stack Overflow用户

发布于 2014-04-15 15:10:49

要获得ListBoxItem,您可以使用ListBoxItemContainerGenerator。确保在加载完成后执行此操作,就像在Loaded事件处理程序中一样,因为在加载之前控件还不存在。

代码语言:javascript
复制
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;
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23087484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档