WPF 遍历ListBox中的控件,遍历数量与ListBox长度不一致的问题

文章讨论了在使用UIVirtualization时,ListBox遍历元素数量不一致的问题。解决方案包括滚动列表以强制可视化所有项,或者通过数据绑定和INotifyPropertyChanged实现元素禁用。示例代码展示了如何修改和绑定IsEnabled属性。
摘要由CSDN通过智能技术生成
 private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
 {
     if (depObj != null)
     {


         var c = VisualTreeHelper.GetChildrenCount(depObj);
         if (c == 36)
         {
             Trace.WriteLine(c);

         }
         for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
         {
             DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
             if (child != null && child is T)
             {
                 yield return (T)child;
             }

             foreach (T childOfChild in FindVisualChildren<T>(child))
             {
                 yield return childOfChild;
             }
         }
     }
 }

这个函数遍历的数量与ListBox长度不一致。
出现这个问题的原因是Listbox控件还没有完成可视化,并且 UI Virtualization 功能正在生效。在使用 UI Virtualization 功能的时候,ListBox 只会把可见的项进行实际的可视化处理,对于屏幕外的项,并不会创建对应的元素。因此,如果调用 ItemContainerGenerator.ContainerFromIndex(index) 方法时,该项元素还没有被实际创建,返回值会为 null。
有两种解决办法:
1.滚动到所有项,再使用FindVisualChildren函数,当然,为了减少遍历次数,也可以间隔滚动。

for(int i =0;i < ListBox.Items.Count;i++)
{
  	object item = ListBox.Items[index];
  	ListBox.ScrollIntoView(item);
};
foreach (System.Windows.Controls.Button btn in FindVisualChildren<System.Windows.Controls.Button>(ListBox))
{
    btn.IsEnabled= false;
}

2.通过绑定的方式(推荐)

ObservableCollection<DataListClass> DataList= new ObservableCollection<DataListClass>();

ListBox.ItemsSource = DataList;

foreach (var Data in DataList)
{
	Data.IsEnabled = false;
}

//-----------------------class--------------------------
public class DataListClass: INotifyPropertyChanged
{
    bool _isenabled ;

    public bool IsEnabled 
    {
        get { return _isenabled ; }
        set { _isenabled = value; FirePropertyChanged("IsEnabled "); }
    }

    public virtual event PropertyChangedEventHandler PropertyChanged;

    public virtual void FirePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

xaml:

<ListBox>
 <ListBox.ItemTemplate>
     <DataTemplate>
         <WrapPanel>
             <Button IsEnabled="{Binding IsEnabled}">
             </Button>
         </WrapPanel>
     </DataTemplate>

 </ListBox.ItemTemplate>
</ListBox>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值