【问题标题】:What is data context in UWP?UWP 中的数据上下文是什么?
【发布时间】:2021-11-21 10:52:23
【问题描述】:
public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}

这里相当于

public string Name{ get; set; } right? 

类变量也是如此

public NewsItem ns { get { return this.DataContext as  NewsItem; } }

public NewsItem ns{get;}

他们是一样的吗???? 如果不是,公共 NewsItem ns{get;}

中的默认返回值将是什么

this.DataContext 的含义是什么

public NewsItem ns { get { return this.DataContext as  NewsItem; } }

如果代码是这样的,返回值是什么

public NewsItem ns { get { return this.DataContext} }

提前致谢

【问题讨论】:

  • 如果答案已经解决了您的问题,请mark它被接受

标签: data-binding uwp uwp-xaml datacontext


【解决方案1】:

public string Name{ get; set; }public string Name{ get { return name; }... 之间的区别

在 C# 3.0 及更高版本中,(上一个)auto-implemented properties 在属性访问器中不需要额外的逻辑时使属性声明更加简洁。它们还使客户端代码能够创建对象。最后一个是普通的property,它是一个提供灵活机制来读取、写入或计算私有字段值的成员。

public NewsItem ns { get { return this.DataContext as NewsItem; } }

FrameworkElement 的DataContext。数据上下文的常见用途是当 FrameworkElement 使用 {Binding} 标记扩展并参与数据绑定时。如果要DataContext可以看成NewsItem。当页面初始化时,您需要将 NewsItem 实例传递给 DataContext。

public TestPage()
{
    this.InitializeComponent();
    this.DataContext = new NewsItem();
}

如果代码是这样的public NewsItem ns { get { return this.DataContext} },返回值是什么

请参考上面的描述,如果你调用nsget方法,它会返回一个NewsItem实例,该实例被评估为当前DataContext

【讨论】:

  • 珠海,如果这样。最初没有分配数据上下文,这些 ``` public NewsItem ns { get { return this.DataContext ; 的返回值是什么? } } ``` ``` public NewsItem ns { get ; } ```
  • 如果DataContext没有赋值,调用NewsItem get方法时会返回null。
【解决方案2】:

您的第一个 Name 属性返回 name 字段的值。第二个是自动实现的属性,它返回您在代码中看不到的编译器生成的字段值的值。它们不是等价的。

public NewsItem ns { get { return this.DataContext as NewsItem; } } 返回DataContext 属性的当前值如果 它已被设置为NewsItem 值。否则返回null

public NewsItem ns {get;} 返回ns 属性的当前值,该值将是null,除非您在某处明确将其设置为某个值。所以他们不一样。

所以要回答您的问题,DataContext 属性的默认值为null,因此您必须设置它才能绑定到它的某些属性。

它不是由框架为您设置的,除非它是从可视化树中的父元素继承的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2021-01-16
    • 2014-01-24
    相关资源
    最近更新 更多