2016-02-19 47 views
0

问题:我有一个简单的cboBox调用PhoneTypes。我希望它的数据源理想地是从linq生成的一个sortedList,它从tblPhonetypes中提取数据。 我也想组合框被绑定。创建一个列表来填充Linq到SQL查询的组合框

​​

在主窗口中我有:

public partial class MainWindow : MetroWindow 
{ 
    public Window mainWindow;  
    public PhoneType selectedPhoneType { get; set; } 

// do we need to have a getter/setter on a list to data bind to?? 
//  public List<PhoneType> phonetypelist {get;set;) 
// not sure if we need an implementation of data context here ! 
// DocITDatabaseEntities ctx = new DocITDatabaseEntities(); 

public MainWindow() 
    { 
     InitializeComponent(); 
     DocITDatabaseEntities ctx = new DocITDatabaseEntities(); 
     DataContext = this; 
     cboPtPhoneType.ItemsSource = phonetypelist; 
     cboPtPhoneType.DataContext = // todo;   
    } 
    private SortedList(int,string) phonelist() 
    { 
     DocITDatabaseEntities ctx = new DocITDatabaseEntities(); 
     List<PhoneType> lstphones = from p in ctx.tblPhoneTypes 
            orderby p.charPhoneType 
            select p; 
     // To do...create the list and pass it to the combo box as the  
    } 

回答

1

如果我理解正确的话,你现在想有lstphones绑定到一个名为cboPhoneType正确的组合框?

因此,确保列表可以从您的DataContext访问,到目前为止,lstphones只存在于phonelist()的范围内。您需要将其设置为MainWindow类的属性,并在您的phonelist()方法内分配列表,并确保在列表的“set”中引发INotifyPropertyChanged事件。

然后,你需要在你的XAML做的最后一件事是:

<ComboBox ItemsSource="{Binding yourList}" SelectedValue="{Binding selectedPhoneType}" /> 

如果我可以,你应该看看MVVM模式将极大地帮助你在WPF