【问题标题】:DataContext and Binding not working in UWPDataContext 和绑定在 UWP 中不起作用
【发布时间】: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 的源对象?

标签: c# uwp


【解决方案1】:

你不见了

this.DataContext = this;

在您的 MainPage.xaml.cs 构造函数中:

public MainPage()
{
    this.InitializeComponent();

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

我认为 WPF 也一样,所以它对 UWP 来说并不特殊。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-15
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2012-02-08
    • 2016-04-10
    • 2021-03-07
    • 2017-02-15
    相关资源
    最近更新 更多