使用EF和LINQ填充C#/ XAML组合框

时间:2014-06-09 09:30:53

标签: c# wpf linq entity-framework xaml

我目前正在创建一个小型测试应用程序,可以通过Linq填充drodown的列表。我收到一个运行时错误,我可以用指针执行:

C#

egwEntities db = new egwEntities();
var sel = from o in db.dropdownsource select new {o.machine_desc};
TxtProductFamily.ItemsSource = sel;

XAML:

<ComboBox x:Name="TxtProductFamily" Text="{Binding testfield}" HorizontalAlignment="Left" Height="26" Margin="10,182,0,0" VerticalAlignment="Top" Width="319"/>

1 个答案:

答案 0 :(得分:1)

你需要这样做:

var sel = (from o in db.dropdownsource
           select o.machine_desc).ToList();

TxtProductFamily.ItemsSource = sel;

或更多好处是创建一个视图模型:

public class MyViewModel
{

public string MyText {get;set;}
public string MyValue {get;set;}

}

然后:

 var sel = (from o in db.dropdownsource
            select new MyViewModel{
                                   MyText = o.machine_desc,
                                   MyValue = o.SomeColumn
                                  }).ToList<MyViewModel>();

和:

<ComboBox x:Name="TxtProductFamily" Text="{Binding MyText}" HorizontalAlignment="Left" Height="26" Margin="10,182,0,0" VerticalAlignment="Top" Width="319"/>