Scenario is something like this, I am having a MainWindow.xaml where as part of this window I will load a UserControl. This UserControl is actually in some other project and it is added in a ResourceDictionary with a key as below,
<ContentControl x:Key="Template1">
<customcontrol:Template1UserControl/>
</ContentControl>
So in MainWindow.xaml I will refer this key as below,
<ContentControl Content="{StaticResource Template1}"/>
Now, like this I am able to see the Template1UserControl in MainWindow.xaml , but the problem is I don't know how to access the datacontext of Template1UserControl in MainWindow.xaml .
Template1 is like a variable, it can have Template2UserControl tomorrow, which can be anything.
Can anyone please help me to do this in WPF. If I should apply some other strategy over here to access the viewmodel of Template1UserControl , that also is most welcome.
Thanks in advance!
Give the ContentControl
in the MainWindow
an x:Name
:
<ContentControl x:Name="cc" Content="{StaticResource Template1}"/>
...and try to cast the properties:
var theTemplate = cc.Content as ContentControl;
var theUserControl = theTemplate?.Content as UserControl;
var theDataContext = theUserControl?.DataContext;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.