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

本文关键字:SQL to Linq 查询 填充 组合 一个 列表 创建 | 更新日期: 2023-09-27 18:35:35

问题:我有一个简单的cboBox调用PhoneType。我希望它的数据源理想情况下是一个从 linq 到 sql 查询生成的排序列表,该查询从 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       
    }

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

如果我

理解正确,您现在想将lstphones绑定到名为cboPhoneType的组合框,对吗?

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

然后,您需要在 XAML 中执行的最后一件事是:

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

如果可以的话,你应该看看MVVM模式,它将在WPF中对你有很大帮助。