In UWP,we can fetch the children by FindDescendants<> .But in winui, we can't able to do that. By doing with visualhelpertree,It always shows zero count in getchildCount() from the calendarview
I just wanted to know how to fetch the children of calendarview . Also i have tried this but shows me zero child always,
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);
}
}
Simply I have created this function to get the child and called,
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();
}
But this not getting the child ,results is the list of objects here where it always show me zero .
CodePudding user response:
My first guess is that you are calling FindDescendants1() before the control is loaded, in the constructor for example. If your CalendarView
is in a Page
, try calling FindDescendants1() in the Page
's Loaded
event.
But there's another problem in you code below.
var child = (CalendarViewDayItem)VisualTreeHelper.GetChild(parent, i);
You'll get an exception because you're trying to cast every DependencyObject
to a CalendarViewDayItem
. By removing the cast you should get the CalendarViewItems
. Though, I would make the FinDescendants() static and just receive the results:
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;
}
}
}
And use it like this:
this.results = FindChildrenOfType<CalendarViewDayItem>(this.CalendarViewControl);
foreach (var item in this.results)
{
// Do you work here...
}