Reputation: 296
I'm kinda new in WPF and I like to use an existing canvas with a lot of children on another xaml page. I saved it in a global property, and I want to use it like this:
this.DataContext = new TimeDesignerViewModel();
this.myCanvas = (this.DataContext as TimeDesignerViewModel).TdCanvas;
When I load the page, there is nothing on a canvas, but in code-behind, there are the children. What did I do wrong?
Upvotes: 2
Views: 1231
Reputation: 18578
You should never have UIElements
in ViewModels
. Secondly, you can't have two parents of same control in WPF. So if you have one Canvas
child of one window
the same instance of that Canvas
cannot be child of other window/UserControl/Page
.
But if you want to have same layout at both places, what you can do it to define your Canvas as Resource in your Application.Resources
in App.xaml
like
<Application.Resources>
<Canvas x:Key="myCanvas" x:Shared="false">
</Canvas>
</Application.Resources>
Make sure you set x:Shared="false" in order to create new instance on every demand of Resource.
Now wherever you want to have this resource you can directly refer in xaml as {StaticResource myCanvas}
or in code you can have it like Application.Current.Resources["myCanvas"] as Canvas
Upvotes: 3