How to check a type of item in ListBox
Need to find out the type of an element inside a listBox, whether the type is button or radio button or simple string.
Something lie the snippet below:
foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
{
if _item is of type of button
//DO this
else if _ite开发者_JAVA百科m is typeof RadioButton
//Do that
}
Just do:
if( item is Button )
{
// Do something
}
else if( item is RadioButton )
{
// Do something
}
How about this:
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;
}
}
If you just want to check the type use the is keyword like the other questions suggest.
If you actually want to use the item as that type, then often it is better to use the as keyword. This does the check but gives you the actual item after the cast for use, and will prevent fxcop warnings that you would recieve if you use is then as.
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 }
}
If for example you wanted to know the type regardless of what is (rather than limiting to certain controls) you could then use the GetType() method.
foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
{
Type t = _item.GetType();
}
Just use is
?
foreach (ListBoxItem _item in listPhotoAlbum.ItemsSource)
{
if _item is Button
//DO this
else if _item is RadioButton
//Do that
}
精彩评论