数据绑定与组合框的ObservableCollection 不依赖项属性

问题描述:

我有对象的列表(的ObservableCollection subjectlist),并希望通过数据绑定和依赖属性的组合框来显示他们的工作。数据绑定与组合框的ObservableCollection <T>不依赖项属性

WPF Data Binding to a Combo Box

我搜索了计算器,并试图实现克雷格Suchanec在上面的链接的解决方案。 (试过了一整天,现在我只是不明白这有什么错我的代码)

MainWindow.xaml.cs

public partial class MainWindow : Window 
{ 
    public static readonly DependencyProperty SubjectListProperty = 
     DependencyProperty.Register("SubjectList", 
     typeof(ObservableCollection<Subject>), 
     typeof(MainWindow)); 



    private ObservableCollection<Subject> subjectList = new ObservableCollection<Subject>(); 
    Initialization init1; 


    public ObservableCollection<Subject> SubjectList 
    { 
     get { return (ObservableCollection<Subject>)GetValue(SubjectListProperty); } 
     // get { return subjectList; } 

    } 


    public MainWindow() 
    { 
     init1 = new Initialization(); 
     subjectList = init1.createMenuSubject(); 

     InitializeComponent(); 
     //this.comboBox.DataContext = SubjectList; 
    } 
} 

MainWindow.xaml

<Grid> 

    <ComboBox x:Name="comboBox" HorizontalAlignment="Left"VerticalAlignment="Top" Width="120" Margin="321,10,0,0" 
          ItemsSource="{Binding ElementName=mainWindow, Path=SubjectList}" DisplayMemberPath="Name"/> 

    </Grid> 

它的工作,如果我只需设置DataContext并在不依赖属性的情况下工作,但只要我尝试使用依赖项属性进行数据绑定,它就没有,我也没有看到我的实现和链接中给出的解决方案之间的显着差异。

如果有人能够帮助我解决这个问题,我们将非常感激。

+0

请发布您的问题的实际代码,而不是截图。代码格式很简单,只需缩进四个空格。 – Clemens

我看不到任何地方你的代码实际上是设置SubjectList属性的值。

然而,您正在设置subjectList的值,但您绑定到了SubjectList。注意套管的差异。

+0

Omg,谢谢!我将subjectList更改为SubjectList并编写了一个集合。现在它正在工作。 – morrismoss

你应该写:的

public ObservableCollection<Subject> SubjectList 
    { 
     set { base.SetValue(SubjectListProperty, value); } 
     get { return (ObservableCollection<Subject>)base.GetValue(SubjectListProperty); } 
    } 

代替

public ObservableCollection<Subject> SubjectList 
    { 
     set { base.SetValue(SubjectListProperty, value); } 
     get { return subjectList; } 
    } 

或任何其他特设格式。您正在设置subjectList在您的构造函数MainWindow(),但是,它不会设置值SubjectList(与大写字母S)和属性更改事件永远不会引发。删除subjectList

如果你想知道为什么的DataContext方法工作,你要注意它会工作,即使你不使用DepenedencyProperty。但是,如果您实施INotifyPropertyChange,则它也可以与设置元素名称一起使用。

+0

非常感谢。我在构造函数中将subjectList更改为SubjectList并编辑访问器。现在它正在工作! – morrismoss