1

我有一个小测试窗口,如下所示:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox x:Name="Combo" DisplayMemberPath="Word" ItemsSource="{Binding Numbers}" HorizontalAlignment="Left" Margin="115,27,0,0" VerticalAlignment="Top" Width="120" />
    </Grid>
</Window>

使用代码隐藏:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Numbers = new ObservableCollection<NumberWord>
                      {
                          new NumberWord {Number = 1, Word = "One"},
                          new NumberWord {Number = 2, Word = "Two"},
                          new NumberWord {Number = 3, Word = "Three"}
                      };
        Combo.ItemsSource = Numbers;
    }
    public ObservableCollection<NumberWord> Numbers { get; set; }
}

我一直看到我的其他绑定问题的答案,这些问题表明Combo.ItemsSource = Numbers;不需要显式设置,因为我有绑定ItemsSource="{Binding Numbers}"。我也被多次告知我不需要设置一个DataContextonCombo因为整个窗口都是数据上下文,并且Combo继承了这个数据上下文。

我的问题是,为什么我总是——不仅仅是这个组合——ItemsSource在代码后面显式地设置或其他绑定属性。为什么 XAML 数据绑定不起作用?

4

3 回答 3

2

绑定ItemsSource="{Binding Numbers}"需要一个源对象,即具有公共Numbers属性的对象。在您的情况下,这是 MainWindow 实例。

因此,您可以通过以下方式明确设置源:

ItemsSource="{Binding Numbers,
    RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"

或者您通过设置 a 来设置源对象DataContext,例如在后面的代码中:

public MainWindow()
{
    InitializeComponent();
    DataContext = this;
    ...
}

如果Numbers以后需要更改属性的值,还必须添加属性更改通知机制,例如实现INotifyPropertyChanged接口。


这在 MSDN 上的Data Binding Overview文章中得到了很好的解释。

于 2013-10-20T08:10:35.960 回答
1

DataContextDependancyProperties如果未设置本地值,则它是子控件从父控件继承的控件之一。

因此,如果您将DataContextof设置Window为某些东西,包括您在内的子控件ComboBox将拥有它。

现在,在你的情况下,你没有设置DataContext你的,Window因此你BindingItemsSource不工作

如果在窗口的构造函数中,在 initializeComponent 之后执行

DataContext = this;

那么你不需要设置in并且你ItemsSource的绑定将在你的 Combo 上工作。Comboboxcode behindItemsSource

于 2013-10-20T08:11:14.903 回答
0

你需要实现 INotifyPropertyChanged。然后使用:

this.DataContext = this;
于 2013-10-20T08:09:12.187 回答