Reputation: 990
I defined a DataContext for a UserControl at XAML page level as follows (the last line being the relevant one):
<UserControl
x:Class="Sample.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="using:Sample.Models"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768"
d:DesignWidth="1024"
DataContext="data:TestDataCollection">
The aim is to be able to access the DataContext object in the page hosting the UserControl as follows, myUserControl being the x:Name
for the UserControl.
TestDataCollection tdc = myUserControl.DataContext as TestDataCollection;
Everything is working fine with data binding and UI displaying and updating as expected on the UWP platform.
The only one problem is that the above code line is not returning the expected DataContext object. In fact, myUserControl.DataContext during debugging shows a string with a value "data:TestDataCollection" (same as in the above XAML code) rather than an object of type TestDataCollection
.
Here is another strange thing: If I set the DataContext in codebehind as:
this.DataContext = new TestDataCollection();
the problem with be gone, i.e., (myUserControl.DataContext as TestDataCollection) returns the DataContext object as expected.
What am I doing wrong in setting the page DataContext in XAML?
Upvotes: 2
Views: 1280
Reputation: 10015
By using DataContext="data:TestDataCollection"
, you're doing nothing more than setting a string value. If you want a viewmodel object to be set, you have to use following syntax:
<UserControl
x:Class="Sample.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:data="using:Sample.Models"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="768"
d:DesignWidth="1024">
<UserControl.DataContext>
<data:TestDataCollection />
</UserControl.DataContext>
</UserControl>
Note that your usercontrol will also inherit a DataContext
from the page it's used on. So in most scenarios it's not necessary to set it explicitly in your control, while you will still be able to access it in code behind (as it's set by the page implicitly).
Upvotes: 1