【问题标题】:How can I specify a default property to bind to in Silverlight / WPF?如何在 Silverlight / WPF 中指定要绑定的默认属性?
【发布时间】:2010-08-03 23:39:31
【问题描述】:

有没有办法通过 XAML 中的数据绑定指定要由 Path 引用的默认属性?我希望能够做一些类似于 CollectionViewSource 在使用 Binding 时所做的事情。

当您在 XAML 中绑定到 CollectionViewSource 时,它​​会自动将 Path 连接到 View 属性。

例如:{Binding Source={StaticResource cvs}} 与 {Binding Path=View, Source={StaticResource cvs}} 相同

是否可以在自定义的 DependencyObject 或 POCO 中做同样的事情?

【问题讨论】:

    标签: c# wpf silverlight data-binding


    【解决方案1】:

    将您的属性设置为 DataContext。假设你有这个课程:

    public class Person
    {
       public string Name { get; set; }
    
       public Person(string name)
       {
          this.Name = name;
       }
    }
    

    您可以将其设置为 DataContext,在窗口中这样说:

    this.DataContext = new Person("Carlo");
    

    在窗口中你有一个标签,你只需这样做:

    <Label Content="{Binding Name}" />
    

    标签将显示“Carlo”。

    现在,如果您只想将名称用作绑定,您可以在窗口中执行此操作:

    Person p = new Person("Carlo");
    this.DataContext = p.Name;
    

    这在标签中:

    <Label Content="{Binding}" />
    

    【讨论】:

      猜你喜欢
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      • 1970-01-01
      相关资源
      最近更新 更多