当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Enumerate over each item of listbox to compare internal element values

问题描述:

I have a listbox with a data template bound to a list<class> in the program.

<DataTemplate x:Key="pTemplate">

<StackPanel Orientation="Horizontal">

<TextBlock Text="{Binding Ref}" Padding="5,0,0,0"/>

<StackPanel Name="taggedA" Tag="{Binding A}" Orientation="Horizontal">

<TextBlock Name="selectedA" Text="{B}" />

</StackPanel>

<Image Name="ind" Width="40" Height="40" />

</StackPanel>

</DataTemplate>

On button click, I want to go over all the elments of the listbox and check if the stackPanel taggedA's tag == textblock selectedA's text.

This is to be done for each of the items in the list box and the data template is as above. How can this be done?

网友答案:

Easier to compare the binding source directly:

ListBox l = myListBox;
for (int i = 0; i < l.Items.Count; i++)
{
    var boundObject = (MyClass)l.Items[i];
    MessageBox.Show("They are equal? " + (boundObject.A == boundObject.B));
}
网友答案:

I would agree with @dbaseman. But if you are set on doing it you could do the following:

private void button_click(object sender, RoutedEvent e)
{
    foreach(var item in MyListBox.Items)
    {
        ListBoxItem lbi = MyListBox.ItemContainerGenerator.ContainerFromItem(item);
        StackPanel taggedApanel = (lbi.Content as StackPanel).Children[1];
        //Do whatever you need to do here
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: