我在 XAML 页面级别为 UserControl 定义了一个 DataContext,如下所示(最后一行是相关的):
<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">
目标是能够访问托管 UserControl 的页面中的 DataContext 对象,如下所示,myUserControl 是 UserControl 的 x:Name
。
TestDataCollection tdc = myUserControl.DataContext as TestDataCollection;
在 UWP 平台上,数据绑定(bind)和 UI 显示和更新一切正常。
唯一的问题是上面的代码行没有返回预期的 DataContext 对象。事实上,调试期间的 myUserControl.DataContext 显示一个值为“data:TestDataCollection”的字符串(与上述 XAML 代码中的相同),而不是 TestDataCollection
类型的对象。
这是另一件奇怪的事情:如果我将代码隐藏中的 DataContext 设置为:
this.DataContext = new TestDataCollection();
问题消失了,即 (myUserControl.DataContext as TestDataCollection) 按预期返回 DataContext 对象。
我在 XAML 中设置页面 DataContext 时做错了什么?
最佳答案
通过使用 DataContext="data:TestDataCollection"
,您只不过是设置一个 string 值。如果要设置 View 模型对象,则必须使用以下语法:
<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>
请注意,您的用户控件还将从使用它的页面继承 DataContext
。因此在大多数情况下,没有必要在您的控件中显式设置它,同时您仍然可以在代码隐藏中访问它(因为它是由页面隐式设置的)。
关于c# - 在 XAML 页面级别定义的 UserControl DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34396866/