Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# DataContext和绑定在UWP中不起作用_C#_Uwp - Fatal编程技术网

C# DataContext和绑定在UWP中不起作用

C# DataContext和绑定在UWP中不起作用,c#,uwp,C#,Uwp,我是第一次在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);

我是第一次在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吗?需要一个正确的例子为我的情况,谢谢

你失踪了

this.DataContext = this;
在MainPage.xaml.cs构造函数中:

public MainPage()
{
    this.InitializeComponent();

    Person = new PersonModel("Oh My Dog");
    this.DataContext = this;
}

我认为WPF也是一样的,所以它对UWP并不特别。

这在WPF中也不起作用。是什么让您认为
DataContext=“{Binding Person}”
会神奇地将主页实例用作绑定的源对象?