【发布时间】:2019-01-05 21:30:10
【问题描述】:
我是第一次在 UWP 上工作的 wpf-er。我发现 VM 中的 DataContext 和 ResourceDictionary 中的绑定在 UWP 中不起作用:
首先我创建一个模型:
public class PersonModel :BindableBase
{
private string _name = string.Empty;
public string Name { get { return _name; } set { SetProperty(ref _name, value); } }
}
然后我把这个模型放在 MainPage.cs 中:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Person.Name = "Oh My Dog";
}
public PersonModel Person { get; } = new PersonModel();
}
我在 App.xaml 中为 ContentControl 创建样式:
<Application.Resources>
<ResourceDictionary>
<!-- Person -->
<Style x:Key="PersonStyle" TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<TextBlock Text="{Binding Name, Mode=OneWay}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</Application.Resources>
然后在 MainPage.xaml 中放置一个 ContentControl:
<Grid>
<ContentControl Style="{StaticResource PersonStyle}" DataContext="{Binding Person}"/>
</Grid>
但它不起作用,MainPage.xaml 上没有显示任何内容。
是不是因为UWP不支持DataContext?需要一个正确的例子来说明我的情况,谢谢!
【问题讨论】:
-
这在 WPF 中也不起作用。是什么让您认为
DataContext="{Binding Person}"会神奇地将 MainPage 实例用作 Binding 的源对象?