Reputation: 1709
I'm new to WPF and trying to build my first application which is multiviewer of multi streams together for learning purpose.
I have 24 multimedia element on the main window and I want to Fullscreen selected multimedia element when there will be one more click to minimize this full screened media.
Code is like this
foreach (var item in MediaElements)
{
item.LoadedBehavior = MediaState.Manual;
item.MouseEnter += mediaElement1_MouseEnter;
item.MouseLeave += mediaElement1_MouseLeave;
item.Loaded += mediaElement1_Loaded;
item.MouseLeftButtonUp += (o, args) =>
{
if(!fullscreen)
{
ListOfMedia.Children.Remove(item);
this.Content = item;
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
}
else
{
this.Content = ListOfMedia;
ListOfMedia.Children.Add(item);
this.WindowStyle = WindowStyle.SingleBorderWindow;
this.WindowState = WindowState.Normal;
}
fullscreen = !fullscreen;
};
}
When I click it the first time, it's working very well, the window is going on maximum screen size, but when I'm clicking it on next time to minimize it, there is an exception which is saying to me
System.ArgumentException: 'Must disconnect specified child from current parent Visual before attaching to new parent Visual.'
I checked some StackOverflow questions but can't find the correct solution, someone was talking about extension method to delete children from parents tree, I wrote this extension method but I don't know what is the problem and what idea is behind this problem? What I must delete from and what is happening at all.
Please tell me what is happening here.
Upvotes: 3
Views: 5883
Reputation: 2875
The whole idea is that if an element already has a logical parent, then you cannot assign it as another elements child.
Imagine the following set up:
CtCtrl = ContentControl
StPnl = StackPanel
br1 = Border
if(CtCtrl.Content != null)
{
var br1 = CtCtrl.Content as Border;
StPnl.Children.Add(br1);
}
The above will result in System.InvalidOperationException:'Specified element is already the logical child of another elelemt. Disconnect it first.'
You can easily orphan that element before adding it to the StackPanel
by the following code:
if(CtCtrl.Content != null)
{
var br1 = CtCtrl.Content as Border;
CtCtrl.Content = null;
StPnl.Children.Add(br1);
}
And the exception will be gone!
Upvotes: 3