我有一个Listbox,它包含一个类型customer的列表。所以我的Listbox.Items不再是ListItem型了,它是客户型的。
我在customer字段中有一个isActive标志,我想知道如果isActive是真的话,我将如何将背景色设置为红色。
目前我已经尝试过了,但是它不能工作,因为我不能让客户输入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;
}
}编辑:每当我取消选中一个针对活动客户的复选框时,我都会调用一个执行上述代码的方法。每当取消选中活动复选框时,我都会遍历客户并显示所有客户,此时,我希望更改非活动复选框的背颜色,以区分哪些是非活动/活动的。
发布于 2014-04-15 15:15:49
有两种方法可以做到这一点。“正确”的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;
}
}发布于 2014-04-15 15:10:49
要获得ListBoxItem,您可以使用ListBox的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;
}
}
}https://stackoverflow.com/questions/23087484
复制相似问题