如何检查ListBox中的项类型

时间:2010-10-01 14:04:59

标签: c# .net

需要找出listBox中元素的类型,无论类型是按钮还是单选按钮还是简单字符串。

下面的片段有些东西:

foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
                    {
                        if _item is of type of button 
                            //DO this
                        else if _item is  typeof RadioButton
                            //Do that
                    }

4 个答案:

答案 0 :(得分:5)

只是做:

if( item is Button )
{
  // Do something
}
else if( item is RadioButton )
{
  // Do something
}

答案 1 :(得分:3)

如果您只想查看类型,请使用 关键字,就像其他问题一样。

如果您确实希望将该项目用作该类型,那么通常最好使用 as 关键字。这样做会进行检查,但会在演示之后为您提供实际项目,如果您使用 然后 ,则会阻止您收到的fxcop警告。

foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
{
    Button b = _item as Button;
    if (b != null) { // DO this }

    RadioButton rb = _item as RadioButton;
    if (rb != null) { // DO that }
}

例如,如果您想知道类型而不管是什么(而不是限制某些控件),那么您可以使用 GetType()方法。

foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
{
    Type t = _item.GetType();
}

答案 2 :(得分:3)

这个怎么样:

foreach (var _item in listPhotoAlbum.Items)
{
    var radioButton = _item as RadioButton;

    if (radioButton != null)
    {
        //Do with radioButton
        continue;
    }

    var button = _item as Button;

    if (button != null)
    {
        //Do with button
        continue;
    }
}

答案 3 :(得分:1)

只需使用is

foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource) 
{ 
    if _item is Button  
        //DO this 
    else if _item is RadioButton 
        //Do that 
}