创建一个列表以使用Linq到SQL查询填充组合框

时间:2016-02-19 23:48:48

标签: c# wpf linq-to-sql combobox sortedlist

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

class PhoneType 
{
    int _idxPhoneType;
    string _charPhoneType;
    public PhoneType(int idxPhoneType, string charPhoneType)
    {
        this.idxPhoneType = idxPhoneType;
        this.charPhoneType = charPhoneType;
    }
    public int idxPhoneType { get; set; }
    public string charPhoneType { get; set; }
   .....//other properties..such as timestamp...etc
}

在主窗口中,我有:

 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 个答案:

答案 0 :(得分:1)

如果我理解正确,您现在希望将lstphones绑定到名为cboPhoneType的ComboBox吗?

因此,请确保可以从DataContext访问该列表,截至目前,lstphones仅存在于phonelist()的范围内。你需要将它作为MainWindow类的属性,在phonelist()方法中分配列表,并确保在列表的“set”中引发INotifyPropertyChanged事件。

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

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

如果可以的话,你应该看一下MVVM模式,它将在WPF中为你提供很大的帮助