簡體   English   中英

我有一個列表框和復選框,如何找到WPF中選中的復選框數量

[英]i have a listbox and check box and how can i find the how much check box checked in wpf

我想查找代碼選中了多少復選框:

 <Grid Width="440" >

<ListBox Name="listBoxZone" ItemsSource="{Binding TheList}"  Background="White" Margin="0,120,2,131">  
      <ListBox.ItemTemplate>
            <HierarchicalDataTemplate>
  <CheckBox Name="CheckBoxZone" Content="{Binding StatusName}" Tag="{Binding StatusId}" Margin="0,5,0,0" VerticalAlignment ="Top"   />
             </HierarchicalDataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

      </Grid>

這是我要查找選中多少復選框的代碼?

for (int i = 0; i < listBoxZone.Items.Count; i++)
                    {
                        if (CheckBoxZone.IsChecked == true )
                        { 


                        }

                    }

您可以將Nullable<bool>類型的IsChecked屬性(可以寫為bool? )添加到數據項類,並雙向綁定CheckBox.IsChecked屬性:

<CheckBox Name="CheckBoxZone" IsChecked={Binding IsChecked, Mode=TwoWay} ... />

現在,您可以簡單地遍歷所有項目並檢查其IsChecked狀態:

int numChecked = 0;
foreach (MyItem item in listBoxZone.Items)
{
    if ((bool)item.IsChecked) // cast Nullable<bool> to bool
    {
        numChecked++;
    }
}

或使用Linq:

int numChecked =
    itemsControl.Items.Cast<MyItem>().Count(i => (bool)i.IsChecked);

請注意:為什么要在ListBox中使用HierarchicalDataTemplate,而DataTemplate就足夠了?

LINQ的OfType方法的使用

int result = 
            listBoxZone.Items.OfType<CheckBox>().Count(i => i.IsChecked == true);

我用OfType ,而不是Cast ,因為OfType會工作,即使有一個復選框項目或所有項目的復選框。

如果使用Cast ,即使沒有一個項目也不會顯示復選框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM