【问题标题】:How can we get the children(calendardayitem) of parent object(calendarview) in winui?我们如何在winui中获取父对象(calendarview)的子对象(calendardayitem)?
【发布时间】:2023-01-29 20:29:19
【问题描述】:

在 UWP 中,我们可以通过 FindDescendants<> 获取孩子。但是在 winui 中,我们不能这样做。 通过使用 visualhelpertree,它总是在 calendarview 的 getchildCount() 中显示零计数

我只是想知道如何获取 calendarview 的孩子。 我也试过这个但总是显示零孩子,

    private void FindDescendants1(DependencyObject parent, Type targetType)
        {
            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            itemchange.Text = childrenCount.ToString();
            for (int i = 0; i < childrenCount; i++)
            {
                var child =(CalendarViewDayItem) VisualTreeHelper.GetChild(parent, i);
                if (child.GetType() == targetType)
                {
                    results.Add(child);
                }
                FindDescendants1(child, targetType);
            }
        }

只是我创建了这个函数来获取孩子并调用,

foreach (DependencyObject displayedDay in results)
        {
            //displayedDay = (CalendarViewDayItem)displayedDay;
            CalendarViewDayItem c = displayedDay as CalendarViewDayItem;
            if (_highlightedDates.Contains(c.Date))
            {
                Console.WriteLine(c.Date.ToString());
                //highlight
                c.Background = new SolidColorBrush(Colors.Red);
            }
            itemchange.Text = c.Date.ToString();
        }

但这没有得到孩子,结果是这里的对象列表,它总是显示为零。

【问题讨论】:

    标签: windows winui-3 winui


    【解决方案1】:

    我的第一个猜测是您在加载控件之前调用 FindDescendants1(),例如在构造函数中。如果您的CalendarViewPage中,请尝试在PageLoaded事件中调用FindDescendants1()。

    但是您在下面的代码中还有另一个问题。

    var child = (CalendarViewDayItem)VisualTreeHelper.GetChild(parent, i);
    

    你会得到一个异常,因为你试图将每个 DependencyObject 转换为 CalendarViewDayItem。通过删除演员表,您应该得到 CalendarViewItems。不过,我会让 FinDescendants() 静态化并只接收结果:

    private static IEnumerable<T> FindDescendantsOfType<T>(DependencyObject parent) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            
            if (child is T hit)
            {
                yield return hit;
            }
    
            foreach (T? grandChild in FindChildrenOfType<T>(child))
            {
                yield return grandChild;
            }
        }
    }
    

    并像这样使用它:

    this.results = FindChildrenOfType<CalendarViewDayItem>(this.CalendarViewControl);
    
    foreach (var item in this.results)
    {
        // Do you work here...
    }
    

    【讨论】:

      猜你喜欢
      • 2022-12-15
      • 2021-01-25
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2020-01-26
      • 2022-01-04
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多