WPF User Control Parent - c#

I have a user control that I load into a MainWindow at runtime. I cannot get a handle on the containing window from the UserControl.
I have tried this.Parent, but it's always null. Does anyone know how to get a handle to the containing window from a user control in WPF?
Here is how the control is loaded:
private void XMLLogViewer_MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem application = sender as MenuItem;
string parameter = application.CommandParameter as string;
string controlName = parameter;
if (uxPanel.Children.Count == 0)
{
System.Runtime.Remoting.ObjectHandle instance = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, controlName);
UserControl control = instance.Unwrap() as UserControl;
this.LoadControl(control);
}
}
private void LoadControl(UserControl control)
{
if (uxPanel.Children.Count > 0)
{
foreach (UIElement ctrl in uxPanel.Children)
{
if (ctrl.GetType() != control.GetType())
{
this.SetControl(control);
}
}
}
else
{
this.SetControl(control);
}
}
private void SetControl(UserControl control)
{
control.Width = uxPanel.Width;
control.Height = uxPanel.Height;
uxPanel.Children.Add(control);
}

Try using the following:
Window parentWindow = Window.GetWindow(userControlReference);
The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.
You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:
this.Loaded += new RoutedEventHandler(UserControl_Loaded);

I'll add my experience. Although using the Loaded event can do the job, I think it may be more suitable to override the OnInitialized method. Loaded occurs after the window is first displayed. OnInitialized gives you chance to make any changes, for example, add controls to the window before it is rendered.

Use VisualTreeHelper.GetParent or the recursive function below to find the parent window.
public static Window FindParentWindow(DependencyObject child)
{
DependencyObject parent= VisualTreeHelper.GetParent(child);
//CHeck if this is the end of the tree
if (parent == null) return null;
Window parentWindow = parent as Window;
if (parentWindow != null)
{
return parentWindow;
}
else
{
//use recursion until it reaches a Window
return FindParentWindow(parent);
}
}

I needed to use the Window.GetWindow(this) method within Loaded event handler. In other words, I used both Ian Oakes' answer in combination with Alex's answer to get a user control's parent.
public MainView()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainView_Loaded);
}
void MainView_Loaded(object sender, RoutedEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
...
}

If you are finding this question and the VisualTreeHelper isn't working for you or working sporadically, you may need to include LogicalTreeHelper in your algorithm.
Here is what I am using:
public static T TryFindParent<T>(DependencyObject current) where T : class
{
DependencyObject parent = VisualTreeHelper.GetParent(current);
if( parent == null )
parent = LogicalTreeHelper.GetParent(current);
if( parent == null )
return null;
if( parent is T )
return parent as T;
else
return TryFindParent<T>(parent);
}

This approach worked for me but it is not as specific as your question:
App.Current.MainWindow

How about this:
DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);
public static class ExVisualTreeHelper
{
/// <summary>
/// Finds the visual parent.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sender">The sender.</param>
/// <returns></returns>
public static T FindVisualParent<T>(DependencyObject sender) where T : DependencyObject
{
if (sender == null)
{
return (null);
}
else if (VisualTreeHelper.GetParent(sender) is T)
{
return (VisualTreeHelper.GetParent(sender) as T);
}
else
{
DependencyObject parent = VisualTreeHelper.GetParent(sender);
return (FindVisualParent<T>(parent));
}
}
}

I've found that the parent of a UserControl is always null in the constructor, but in any event handlers the parent is set correctly. I guess it must have something to do with the way the control tree is loaded. So to get around this you can just get the parent in the controls Loaded event.
For an example checkout this question WPF User Control's DataContext is Null

Another way:
var main = App.Current.MainWindow as MainWindow;

It's working for me:
DependencyObject GetTopLevelControl(DependencyObject control)
{
DependencyObject tmp = control;
DependencyObject parent = null;
while((tmp = VisualTreeHelper.GetParent(tmp)) != null)
{
parent = tmp;
}
return parent;
}

This didn't work for me, as it went too far up the tree, and got the absolute root window for the entire application:
Window parentWindow = Window.GetWindow(userControlReference);
However, this worked to get the immediate window:
DependencyObject parent = uiElement;
int avoidInfiniteLoop = 0;
while ((parent is Window)==false)
{
parent = VisualTreeHelper.GetParent(parent);
avoidInfiniteLoop++;
if (avoidInfiniteLoop == 1000)
{
// Something is wrong - we could not find the parent window.
break;
}
}
Window window = parent as Window;
window.DragMove();

If you just want to get a specific parent, not only the window, a specific parent in the tree structure, and also not using recursion, or hard break loop counters, you can use the following:
public static T FindParent<T>(DependencyObject current)
where T : class
{
var dependency = current;
while((dependency = VisualTreeHelper.GetParent(dependency) ?? LogicalTreeHelper.GetParent(dependency)) != null
&& !(dependency is T)) { }
return dependency as T;
}
Just don't put this call in a constructor (since the Parent property is not yet initialized). Add it in the loading event handler, or in other parts of your application.

DependencyObject parent = ExVisualTreeHelper.FindVisualParent<UserControl>(this);

DependencyObject GetTopParent(DependencyObject current)
{
while (VisualTreeHelper.GetParent(current) != null)
{
current = VisualTreeHelper.GetParent(current);
}
return current;
}
DependencyObject parent = GetTopParent(thisUserControl);

The Window.GetWindow(userControl) will return the actual window only after the window was initialized (InitializeComponent() method finished).
This means, that if your user control is initialized together with its window (for instance you put your user control into the window's xaml file), then on the user control's OnInitialized event you will not get the window (it will be null), cause in that case the user control's OnInitialized event fires before the window is initialized.
This also means that if your user control is initialized after its window, then you can get the window already in the user control's constructor.

Gold plated edition of the above (I need a generic function which can infer a Window within the context of a MarkupExtension:-
public sealed class MyExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider) =>
new MyWrapper(ResolveRootObject(serviceProvider));
object ResolveRootObject(IServiceProvider serviceProvider) =>
GetService<IRootObjectProvider>(serviceProvider).RootObject;
}
class MyWrapper
{
object _rootObject;
Window OwnerWindow() => WindowFromRootObject(_rootObject);
static Window WindowFromRootObject(object root) =>
(root as Window) ?? VisualParent<Window>((DependencyObject)root);
static T VisualParent<T>(DependencyObject node) where T : class
{
if (node == null)
throw new InvalidOperationException("Could not locate a parent " + typeof(T).Name);
var target = node as T;
if (target != null)
return target;
return VisualParent<T>(VisualTreeHelper.GetParent(node));
}
}
MyWrapper.Owner() will correctly infer a Window on the following basis:
the root Window by walking the visual tree (if used in the context of a UserControl)
the window within which it is used (if it is used in the context of a Window's markup)

Different approaches and different strategies. In my case I could not find the window of my dialog either through using VisualTreeHelper or extension methods from Telerik to find parent of given type. Instead, I found my my dialog view which accepts custom injection of contents using Application.Current.Windows.
public Window GetCurrentWindowOfType<TWindowType>(){
return Application.Current.Windows.OfType<TWindowType>().FirstOrDefault() as Window;
}

Related

Find control's ancestor by type

I have a UserControl 'child' within another UserControl (that's acting as a TabItem in a TabControl). Between the child UserControl and the TabItem ancestor are a number of other controls (eg: Grids, a StackPanel, possibly a ScrollViewer, etc).
I want to access a property of the TabItem UserControl in my child UserControl and customised a commonly suggested recursive function that walks up the Visual tree. However, this always returned true at the first null check until I added a query on the Logical tree.
Code:
public MyTabItem FindParentTabItem(DependencyObject child)
{
DependencyObject parent = VisualTreeHelper.GetParent(child) ?? LogicalTreeHelper.GetParent(child);
// are we at the top of the tree
if (parent == null)
{
return null;
}
MyTabItem parentTabItem = parent as MyTabItem;
if (parentTabItem != null)
{
return parentTabItem;
}
else
{
//use recursion until it reaches the control
return FindParentTabItem(parent);
}
}
Unfortunately, this too returns null. When stepping through the method, I see it does find the correct UserControl TabItem, but then as it recurses(?) back through the returns, it reverts this back to null which is then returned to the calling method (in the child UserControl's Loaded event):
MyTabItem tab = FindParentTabItem(this);
How do I fix this so my method correctly returns the found MyTabItem?
Here's a working Unit-Tested solution.
public static T FindAncestor<T>(DependencyObject obj)
where T : DependencyObject
{
if (obj != null)
{
var dependObj = obj;
do
{
dependObj = GetParent(dependObj);
if (dependObj is T)
return dependObj as T;
}
while (dependObj != null);
}
return null;
}
public static DependencyObject GetParent(DependencyObject obj)
{
if (obj == null)
return null;
if (obj is ContentElement)
{
var parent = ContentOperations.GetParent(obj as ContentElement);
if (parent != null)
return parent;
if (obj is FrameworkContentElement)
return (obj as FrameworkContentElement).Parent;
return null;
}
return VisualTreeHelper.GetParent(obj);
}
Usage would be
FindAncestor<MyTabItemType>(someChild);
Edit:
Let's assume your xaml looks like what you describe it as:
<UserControl>
<Grid></Grid>
<StackPanel></StackPanel>
<!-- Probably also something around your child -->
<Grid>
<UserControl x:Name="child"/>
</Grid>
</UserControl>
You're currently in your child-xaml.cs
void OnChildUserControlLoaded(object sender, RoutedEventArgs e)
{
var parent = FindAncestor<ParentUserControlType>(this);
DoSomething(parent.SomeProperty);
}
Unless you do something you did not describe the code will work as is.
I suggest you provide a MCVE with all necessary information.

Hiding the ellipsis within an AppBar

When you create an AppBar or a CommandBar in a UWP app, there's always an ellipsis hiding near the side of the control, like so:
I don't want it in my app but I haven't found any methods/properties within AppBarthat would help me get rid of it. It should be possible, because many of the default Windows 10 apps don't have it. For example, there's no ellipsis on the main menu bar below:
Is it possible to hide the ellipsis using AppBar, or do I have to use a SplitView or some other control to implement this?
First, try not to use AppBar in your new UWP apps.
The CommandBar control for universal Windows apps has been improved to
provide a superset of AppBar functionality and greater flexibility in
how you can use it in your app. You should use CommandBar for all new
universal Windows apps on Windows 10.
You can read more about it here.
Both CommandBar and AppBar can be full styled and templated. This gives you the ability to remove whatever UI elements you don't want to display.
This is how you do it -
Open your page in Blend, right click on CommandBar > Edit Template > Edit a Copy. Then make sure you select Define in Application as currently there's a bug in Blend which will fail to generate the styles if you choose This document.
Once you have all the styles, find the MoreButton control and set its Visibility to Collapsed (or you can remove it but what if you realise you need it later?).
Then you should have a CommandBar without the ellipsis.
Update for 2017
The visibility of the Ellipsis button can now be found in the OverflowButtonVisibility Property of a CommandBar. As above set it to Collapsed to hide it.
If you want to hide this button globally it enough to add
<Style x:Key="EllipsisButton" TargetType="Button">
<Setter Property="Visibility" Value="Collapsed"/>
</Style>
to global resource file
I know this question is is not active any more, but for sake of completion I am proposing my answer.
Instead of changing the visibility by using Styles, I have written an AttachedProperty extension that is able to hide/show the MoreButton via data binding. This way you can show/hide it conditionally as you please.
Usage is as simple as binding your property to the extension:
<CommandBar extensions:CommandBarExtensions.HideMoreButton="{Binding MyBoolean}">
...
</CommandBar>
The extension code is as follows:
public static class CommandBarExtensions
{
public static readonly DependencyProperty HideMoreButtonProperty =
DependencyProperty.RegisterAttached("HideMoreButton", typeof(bool), typeof(CommandBarExtensions),
new PropertyMetadata(false, OnHideMoreButtonChanged));
public static bool GetHideMoreButton(UIElement element)
{
if (element == null) throw new ArgumentNullException(nameof(element));
return (bool)element.GetValue(HideMoreButtonProperty);
}
public static void SetHideMoreButton(UIElement element, bool value)
{
if (element == null) throw new ArgumentNullException(nameof(element));
element.SetValue(HideMoreButtonProperty, value);
}
private static void OnHideMoreButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var commandBar = d as CommandBar;
if (e == null || commandBar == null || e.NewValue == null) return;
var morebutton = commandBar.FindDescendantByName("MoreButton");
if (morebutton != null)
{
var value = GetHideMoreButton(commandBar);
morebutton.Visibility = value ? Visibility.Collapsed : Visibility.Visible;
}
else
{
commandBar.Loaded += CommandBarLoaded;
}
}
private static void CommandBarLoaded(object o, object args)
{
var commandBar = o as CommandBar;
var morebutton = commandBar?.FindDescendantByName("MoreButton");
if (morebutton == null) return;
var value = GetHideMoreButton(commandBar);
morebutton.Visibility = value ? Visibility.Collapsed : Visibility.Visible;
commandBar.Loaded -= CommandBarLoaded;
}
}
On initial binding it uses the Loaded event to apply the hiding once it has been loaded. The FindDescendantByName is another extension method that iterates the visual tree. You might want to create or grab one if your solution does not yet contain it.
Since I cannot add a comment to the particular answer I'll post it here.
The following page gives many examples that will find the child object to compliment #RadiusK's answer.
How can I find WPF controls by name or type?
The one that worked for me specifically in UWP was:
/// <summary>
/// Finds a Child of a given item in the visual tree.
/// </summary>
/// <param name="parent">A direct parent of the queried item.</param>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="childName">x:Name or Name of child. </param>
/// <returns>The first parent item that matches the submitted type parameter.
/// If not matching item can be found,
/// a null parent is being returned.</returns>
public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
{
// Confirm parent and childName are valid.
if (parent == null)
return null;
T foundChild = null;
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
// If the child is not of the request child type child
T childType = child as T;
if (childType == null)
{
// recursively drill down the tree
foundChild = FindChild<T>(child, childName);
// If the child is found, break so we do not overwrite the found child.
if (foundChild != null)
break;
}
else if (!string.IsNullOrEmpty(childName))
{
var frameworkElement = child as FrameworkElement;
// If the child's name is set for search
if (frameworkElement != null && frameworkElement.Name == childName)
{
// if the child's name is of the request name
foundChild = (T)child;
break;
}
}
else
{
// child element found.
foundChild = (T)child;
break;
}
}
return foundChild;
}
Calling the code like this:
var morebutton = FindChild<Button>(commandBar, "MoreButton");
Building upon #RadiusK's answer (which has some issues), I came up with a conciser alternative that's tested and works:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace Linq
{
public static class CommandBarExtensions
{
public static readonly DependencyProperty HideMoreButtonProperty = DependencyProperty.RegisterAttached("HideMoreButton", typeof(bool), typeof(CommandBarExtensions), new PropertyMetadata(false, OnHideMoreButtonChanged));
public static bool GetHideMoreButton(CommandBar d)
{
return (bool)d.GetValue(HideMoreButtonProperty);
}
public static void SetHideMoreButton(CommandBar d, bool value)
{
d.SetValue(HideMoreButtonProperty, value);
}
static void OnHideMoreButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var CommandBar = d as CommandBar;
if (CommandBar != null)
{
var MoreButton = CommandBar.GetChild<Button>("MoreButton") as UIElement;
if (MoreButton != null)
{
MoreButton.Visibility = !(e.NewValue as bool) ? Visibility.Visible : Visibility.Collapsed;
}
else CommandBar.Loaded += OnCommandBarLoaded;
}
}
static void OnCommandBarLoaded(object sender, RoutedEventArgs e)
{
var CommandBar = sender as CommandBar;
var MoreButton = CommandBar?.GetChild<Button>("MoreButton") as UIElement;
if (MoreButton != null)
{
MoreButton.Visibility = !(GetHideMoreButton(CommandBar) as bool) ? Visibility.Visible : Visibility.Collapsed;
CommandBar.Loaded -= OnCommandBarLoaded;
}
}
public static T GetChild<T>(this DependencyObject Parent, string Name) where T : DependencyObject
{
if (Parent != null)
{
for (int i = 0, Count = VisualTreeHelper.GetChildrenCount(Parent); i < Count; i++)
{
var Child = VisualTreeHelper.GetChild(Parent, i);
var Result = Child is T && !string.IsNullOrEmpty(Name) && (Child as FrameworkElement)?.Name == Name ? Child as T : Child.GetChild<T>(Name);
if (Result != null)
return Result;
}
}
return null;
}
}
}

Accessing MainWindow's controls from a user control page. WPF C#

I have a page transition ( a control ) in the MainWindow , I have many user control pages , I want to access the page transition in the MainWindow from my user control page ? How do I do that?
I tried :
Story page = new Story();
NavigationService nav = NavigationService.GetNavigationService(this);
// Navigate to the page, using the NavigationService
// if (nav != null)
// {
// nav.Navigate(page);
MainWindow test = new MainWindow();
test.pageTransition1.ShowPage(page);
// }
Application.Current.MainWindow
Using this you can access the MainWindow from any place.
You could find the WpfPageTransitions.PageTransition control like this from the UserControls code behind:
public static WpfPageTransitions.PageTransition FindPageControl(DependencyObject child)
{
DependencyObject parent= VisualTreeHelper.GetParent(child);
if (parent == null) return null;
WpfPageTransitions.PageTransition page = parent as WpfPageTransitions.PageTransition;
if (page != null)
{
return page;
}
else
{
return FindPageControl(parent);
}
}
Then you can use it like this:
this.FindPageControl(this).ShowPage(...);
Create A Method Inside Main Window for Choosing Page Transition
public void ChangePage()
{
pageTransitionControl.ShowPage(new NewData());
}
Then in Child control
private void btnUpdate_Click(object sender,RoutedEventArgs e)
{
MainWindow win = (MainWindow)Window.GetWindow(this);
win.ChangePage();
}

Attached behaviour on parent mvvm doesn't work

I have 2 Usercontrols, parent and child, child control has button witch I want to click with parent viewmodel method, but it doesn't work, please tell me what I miss
in parent view, I have something like this:
XAML
...
<view:childUC vm:ChildBehaviuor.AddCommand="{Binding ExampleCommand}"/>
Behavior code:
public static readonly DependencyProperty AddCommandProperty =DependencyProperty.RegisterAttached
(
"AddCommand",
typeof(ICommand),
typeof(childBehavior),
new PropertyMetadata(OnAddCommand)
);
public static ICommand GetAddCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(AddCommandProperty);
}
public static void SetAddCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(AddCommandProperty,value);
}
private static ICommand command;
private static void OnAddCommand(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
child gp = sender as child;
childBehavior.command = (ICommand)sender.GetValue(childBehavior.AddCommandProperty);
if(gp != null && command != null)
{
if ((e.NewValue != null) && (e.OldValue == null))
{
gp.AddButton.Click += ButtonClick;
}
else if ((e.NewValue == null) && (e.OldValue != null))
{
gp.AddButton.Click -= ButtonClick;
}
}
}
public static void ButtonClick(object sender,RoutedEventArgs eventArgs)
{
childBehavior.command.Execute(null);
}
VM parent command:
public ICommand ExampleCommand
{
get
{
if (this.exampleCommand == null)
{
this.exampleCommand = new DelegateCommand(...);
}
return this.exampleCommand ;
}
}
I am not sure if I understood you but if you are looking for a way to execute a command on your child usercontrol when you click a button in your parent usercontrol you need to do following:
Let your parent usercontrol implement ICommandSource interface which contains a property called "Command".
Bind the certain command which is in your child usercontrol to the "Command" property which you will have available on your parent usercontrol after you implement ICommandSource interface.
When you click on your button which is in your parent usercontrol, access inside the button handler, which is a method in your parent usercontrol, the available Command propery that you got though the interface. After accessing the Command property call Command.Execute() method, which will go to your child usercontrol and trigger the command you binded before.
Thats how you execute an command on child usercontrol from parent usercontrol.. if you want it the other way around you just have to replace every child word with parent, and every parent word with child :)

getting value of listview from a child window to another child window

in vb6 i can easily get the value from childwindow to another childwindow.. for example frm1.textbox1.text = frm2.listview.item.selectedindex... how can i do this in wpf?
i have two child window named EmployeProfile and the other one is PrintEmpProfile... in EmployeeProfile window, there is a listview... what i want is if I'm going to click the print button, i can get the value from EmployeeProfile listview....
so far this is what's I've got. this code is inside of PrintEmpProfile
DataTable table = new DataTable("EmpIDNumber");
table.Columns.Add("IDNum", typeof(string));
for (int i = 1; i <= 100; i++)
{
table.Rows.Add(new object[] { EmployeeProfile.????? });
}
i don't know how to get all values from EmployeeProfile listview.
Whenever you open a child window put a reference of the new child window into a collection. I ssume that MyChild is your child window defined in XAML like:
<Window
x:Class="TEST.MyChild"
...
You can define a static list holding your child windows in App.xaml.cs
public partial class App : Application
{
public static List<MyChild> Children
{
get
{
if (null == _Children) _Children = new List<MyChild>();
return _Children;
}
}
private static List<MyChild> _Children;
}
Whenever you open child window add it into this collection like:
MyChild Child = new MyChild();
App.Children.Add(Child);
Child.Show();
You should also remove child from this collection when you close your child window. You can do this in Closed event of the window. Define closed vent in XML:
Closed="MyChild_Closed"
And in code behind:
private void MyChild_Closed(object sender, EventArgs e)
{
// You may check existence in the list first in order to make it safer.
App.Children.Remove(this);
}
Whenever a child window wants to access ListView of other child window then it gets reference of the child from the collection and then call ListView defined in XAML directly.
MyChild ChildReference = App.Children.Where(x => x.Title == "Child Title").FirstOrDefault();
if (null != ChildReference)
{
ChildReference.listview.SelectedIndex = ...
}
You can create Property Of listview .
public ListView EmployeeListView
{
get
{
return IdOfYourListView;
}
set
{
IdOfYourListView = value;
}
}
Now on PrintEmpProfile Create object of EmployeeProfile
EmployeeProfile empf = new EmployeeProfile();
ListView MyListView = empf.EmployeeListView;

Categories

Resources