简体   繁体   English

如何以编程方式在ListboxItem上设置IsChecked属性?

[英]How to programmatically set IsChecked property on ListboxItem?

I have a listbox, which I fill with a list via ItemsSource = list. 我有一个列表框,我通过ItemsSource = list填充列表。

Now, I have another list. 现在,我有另一个清单。 And what I want to do is loop through the ListBox, to see if the ListBoxItem.Name is the same. 我想要做的是遍历ListBox,看看ListBoxItem.Name是否相同。 If so, then the ListBoxItem should be selected. 如果是,则应选择ListBoxItem。

My idea: 我的点子:

List<string> firstList = new List<string>();
List<string> secondList = new List<string>();

Listboxx.ItemsSource = firstList;

foreach (string striing in secondList)
{
   foreach (ListBoxItem iitem in Listboxx)
   {
       if (striing == iitem.Name)
       {
          iitem.IsSelected = true;
       }
   }
 }

Or is there a way in the ListboxItemTemplate to set the IsChecked bool to {Binding IsCheckedOrNot}? 或者ListboxItemTemplate中有没有办法将IsChecked bool设置为{Binding IsCheckedOrNot}?

Nested loops generally should be avoided when possible. 一般情况下应尽可能避免使用嵌套循环。 Why not do something like this? 为什么不做这样的事情?

foreach(var iitem in Listboxx.Items.Where(i => secondList.Contains(i.Name)))
{
    iitem.IsSelected = true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何动画IsChecked属性? - How to animate IsChecked property? 如何以声明方式从ComboBox的内容设置RadioButton的IsChecked属性? - How to set the IsChecked property of a RadioButton from the Contents of a ComboBox declaratively? 如何更新ListBoxItem属性 - How to update ListBoxItem property 如何通过绑定到 ViewModel 将正确的 RadioButton.IsChecked 属性设置为 True? - How To Set The Correct RadioButton.IsChecked Property True By Binding To A ViewModel? 在WPF中的ListBoxItem上触发触发器时,如何设置父元素的属性 - How to set a property of the parent element, when firing a trigger on ListBoxItem in WPF WPF:以编程方式更改 MouseOver 的 ListBoxItem 背景属性 - WPF: Change ListBoxItem Background property for MouseOver programmatically 如何通过触发器在其父对象的IsChecked属性上设置图像的效果? - How can I set an Image's effect via trigger on its parent's IsChecked property? 如何绑定菜单项的IsChecked属性 - How to Bind IsChecked Property of Menu item 如何通过XAML为Enum类型的子项设置MenuItem的IsChecked属性? - How to set a MenuItem's IsChecked property for a child of type Enum via XAML? 如何以编程方式设置ItemsSource属性? - How to set ItemsSource property programmatically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM