2013-10-20 72 views
0

我有一个小的测试窗口,如下所示:为什么这个ComboBox数据绑定不起作用?

<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}"。我也被多次告知,我不需要在Combo上设置DataContext,因为整个窗口是数据上下文,并且Combo继承了这个数据上下文。

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

回答

0

DataContextDependancyProperties之一,如果未设置本地值,子控件将从父项继承。

因此,如果您将DataContextWindow设置为某些内容,则包括您的ComboBox的子控件将拥有它。现在

,你的情况,你有没有设置的DataContextWindow因此您的ItemsSourceBinding不工作

如果在窗口的构造函数中,在InitializeComponent后你做

DataContext = this; 

那么您无需在code behind中设置ItemsSourceCombobox,并且您的绑定ItemsSource可用于您的组合。

0

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

this.DataContext = this; 
+0

我不需要实现'INotifyPropertyChanged'因为什么都不改变,而'Numbers'只是数据上下文的一个成员,所以我设置'DataContext = Numbers'将是愚蠢的。其他控件将共享此数据上下文,并希望绑定到“数字”以外的成员。 – ProfK

+0

@ProfK:你说得对,也许最好的选择是使用MVVM的多个控件和单个数据上下文。对不起,我更正了更改的答案this.DataContext = this; – UFO

1

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

因此,无论你通过什么明确设置的来源是这样的:

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

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

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

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


这个问题在MSDN上的Data Binding Overview文章中有很好的解释。