【问题标题】:How to set up a binding in WPF?如何在 WPF 中设置绑定?
【发布时间】:2011-06-07 11:47:23
【问题描述】:

我有一个带有如下字段的窗口:

public partial class VariablesWindow : Window
{
    public Dictionary<string, string> Variables { get; private set; }

然后在窗口的 XAML 中,我创建了一个 ListView。如何将 ItemsSource 设置为绑定到 Variables

<ListView ItemsSource="???"

【问题讨论】:

    标签: wpf data-binding binding


    【解决方案1】:

    我认为 ChrisF 发布的内容会起作用...

    <ListView ItemsSource="{Binding Variables}" /> 
    

    但您可能需要明确设置 DataContext。

    this.DataContext = this;
    

    【讨论】:

    • 是的!也需要设置DataContext。其他答案缺少这个:)
    • @Ralph:不太正确。绑定将正常工作除非有人将DataContext 设置为其他值。
    • @Jon:我之前没有接触过 DataContext 属性...我假设默认情况下它指向控件本身,而不是窗口。
    【解决方案2】:

    我认为以下应该可行:

    <ListView ItemsSource="{Binding Path=Variables}" />
    

    我现在无法仔细检查这一点,所以我不能 100% 确定是否需要 Path=

    在 MSDN herehere 上有更多关于绑定语法的信息。他们所有的例子都有Path=语法。

    你必须设置DataContext

    【讨论】:

      【解决方案3】:
      <ListView ItemsSource="{Binding Path=Variables}" />
      

      但是,您可能会发现直接绑定到键或值更有用,您可以这样做:

      <ListView ItemsSource="{Binding Path=Variables.Values}" />
      

      更新:只要您的DataContextnull 或等于this,这些绑定就会起作用。否则,您将需要使用更麻烦的东西,例如

      <ListView ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=x:Type Window}}, Path=Variables}
      

      如需绑定帮助,请查看this superb cheat sheet

      【讨论】:

      【解决方案4】:

      这行得通,但它有点荒谬的冗长:

      ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:VariablesWindow, AncestorLevel=1}
      

      这似乎不是最好的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-26
        • 2014-04-05
        • 2010-12-27
        • 2011-02-20
        • 1970-01-01
        • 2018-10-11
        相关资源
        最近更新 更多