2016-02-19 65 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