Reputation: 2446
For my WP7 app, I need to find a date control which I have placed in the header template of the pivotitem. How do I access this datepicker control in the code behind 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);
}
}
}
Upvotes: 3
Views: 2426
Reputation: 16826
The regular Parent/Child relationship doesn't really work for the Pivot control. What you can do is search for the DatePicked component directly in the PivotItem:
((DatePicker)((PivotItem)MainPivot.SelectedItem).FindName("DateControl"))
MainPivot is the Pivot control. I am getting the currently selected item via SelectedItem - notice that I am casting it to PivotItem directly, since otherwise I get an object. Then I am looking for a control named DateControl, given that you have a x:Name set for it.
All that needs to be done after that is cast the object to DatePicker and access its properties the same way you would do for any other control.
Upvotes: 1
Reputation: 1640
I don't know of any real good solution to this. I guess my initial thought was why do you need a reference to the DatePicker object? But I guess you have your reasons.
A possible solution though:
You could use the VisualTreeHelper to traverse the visual tree from your pivot item and stop when you find an object of the correct type (DatePicker). Create a helper function like this:
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;
}
Then call it with the PivotItem as the DependencyObject, typeof(DatePicker) as the type and finally cast the returned DependencyObject to a DatePicker.
HTH
Upvotes: 1