[英]How can we get the children(calendardayitem) of parent object(calendarview) in winui?
在 UWP 中,我们可以通过 FindDescendants<> 获取孩子。但是在 winui 中,我们不能这样做。 通过使用 visualhelpertree,它总是在 calendarview 的 getchildCount() 中显示零计数
我只是想知道如何获取日历视图的孩子。 我也试过这个但总是显示零孩子,
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);
}
}
简单地说,我创建了这个 function 来获取孩子并调用,
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();
}
但这没有得到孩子,结果是这里的对象列表,它总是显示为零。
我的第一个猜测是您在加载控件之前调用 FindDescendants1(),例如在构造函数中。 如果您的CalendarView
在Page
中,请尝试在Page
的Loaded
事件中调用 FindDescendants1() 。
但是您在下面的代码中还有另一个问题。
var child = (CalendarViewDayItem)VisualTreeHelper.GetChild(parent, i);
你会得到一个异常,因为你试图将每个DependencyObject
转换为CalendarViewDayItem
。 通过删除演员表,您应该获得CalendarViewItems
。 虽然,我会让 FinDescendants() static 并只收到结果:
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...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.