【问题标题】:Creating a List to Populate a Combo Box with Linq to SQL Query创建列表以使用 Linq to SQL 查询填充组合框
【发布时间】:2016-02-19 23:48:48
【问题描述】:

问题:我有一个简单的 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       
    }

【问题讨论】:

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


    【解决方案1】:

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

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

    那么,您需要在 XAML 中做的最后一件事是:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      相关资源
      最近更新 更多