WP7 finds control inside pivotium header

For my WP7 application, I need to find the date control that I placed in the pivotitem header template. How to access this date control in code for the currently selected PivotItem?

public static T FindName<T>(string name, DependencyObject reference) where T : FrameworkElement
{
    if (string.IsNullOrEmpty(name))
    {
        throw new ArgumentNullException("name");
    }

    if (reference == null)
    {
        throw new ArgumentNullException("reference");
    }

    return FindNameInternal<T>(name, reference);
}

private static T FindNameInternal<T>(string name, DependencyObject reference) where T : FrameworkElement
{
    foreach (DependencyObject obj in GetChildren(reference))
    {
        T elem = obj as T;

        if (elem != null && elem.Name == name)
        {
            return elem;
        }

        elem = FindNameInternal<T>(name, obj);

        if (elem != null)
        {
            return elem;
        }
        else
        {
            //if (obj.GetType().FullName == "System.Windows.Controls.DataField")
            //    elem = (obj as DataField).Content as T;

            if (elem != null && elem.Name == name)
                return elem;
        }
    }
    return null;
}

private static IEnumerable<DependencyObject> GetChildren(DependencyObject reference)
{
    int childCount = VisualTreeHelper.GetChildrenCount(reference);

    if (childCount > 0)
    {
        for (int i = 0; i < childCount; i++)
        {
            yield return VisualTreeHelper.GetChild(reference, i);
        }
    }
}
+3
source share
2 answers

I do not know a single real good solution to this. I think my initial thought was related to why you need a reference to a DatePicker object? But I think you have your own reasons.

:
VisualTreeHelper, , (DatePicker). :

private static DependencyObject GetDependencyObjectFromVisualTree(DependencyObject startObject, Type type)
{
    DependencyObject parent = startObject;

    while (parent != null)
    {
        if (type.IsInstanceOfType(parent))
            break;

        parent = VisualTreeHelper.GetParent(parent);
    }

    return parent;
}

PivotItem DependencyObject, typeof (DatePicker) , , DependencyObject DatePicker.

+1

"/" Pivot. DatePicked PivotItem:

((DatePicker)((PivotItem)MainPivot.SelectedItem).FindName("DateControl"))

MainPivot - Pivot. SelectedItem - , PivotItem , . DateControl, , x: Name.

, , DatePicker , .

+1

Source: https://habr.com/ru/post/1776089/


All Articles