我在 WPF 应用程序中使用 EntityFramework 库,但遇到以下问题: 我正在使用 MVVM 模式(据我所知),并且我正在尝试使用 EF 值进行组合框查找。
- 我有一个 Company 类,其中包含许多 Office(也是一个类)
- 这是通过 EntityFramework 建模的,所有链接都是正确的(Office 有一个 CompanyName,它是外键)。
这是 OfficeView 类:
public partial class AddOffice : Window
{
private DBHelper.ResourceManagementContext context = new DBHelper.ResourceManagementContext();
public AddOffice()
{
InitializeComponent();
context.Companies.Load();
this.DataContext = context.Companies.Local;
//this.DataContext = new AddOfficeViewModel();
}
public void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
this.Close();
}
}
下面是相应的 XAML:
<Label Grid.Row="4" Grid.Column="0" Margin="10,10">Company:</Label>
<ComboBox Grid.Row="4" Grid.Column="1" Margin="10,10"
ItemsSource="{Binding}"
DisplayMemberPath="CompanyName"
SelectedValuePath="CompanyName"
SelectedValue="{Binding Path=CompanyName}"/>
我知道 MVVM 模式通常将 ViewModel 传递给 View ,那么如何使用 OfficeViewModel 将 EntityFramework 公司列表绑定(bind)到 ComboBox?
我了解 ComboBox 属性。我知道所选值将是 Office 对象中的 CompanyName,SeletecValuePath 将是 Company 对象中的 CompanyName。
最佳答案
在 View 模型中:
class OfficeViewModel
{
private string _CompanyName;
public string CompanyName
{
get
{
return _CompanyName;
}
set
{
_CompanyName = value;
NotifyPropertyChanged("CompanyName");
}
}
private List<Location> _CompanyList;
public List<Location> CompanyList
{
get
{
return _CompanyList;
}
set
{
_CompanyList = value;
NotifyPropertyChanged("CompanyList");
}
}
public List<Company> GetCompanyList()
{
return (from comp in Entity.Companies select comp).ToList();
}
}
在 Xaml 中:
在xaml中添加命名空间,如下:
xmlns:ViewModels="clr-namespace:WpfMvvmApplication.ViewModels"
在window.resources中添加以下内容:
<Window.Resources>
<ViewModels:OfficeViewModel x:Key="OfficeController"/>
</Window.Resources>
将 View 模型绑定(bind)到组合框:
<Label Grid.Row="4" Grid.Column="0" Margin="10,10">Company:</Label>
<ComboBox Grid.Row="4" Grid.Column="1" Margin="10,10"
ItemsSource="{Binding CompanyList, Source={StaticResource OfficeController}}"
DisplayMemberPath="CompanyName"
SelectedValuePath="CompanyName"
SelectedValue="{Binding Path=CompanyName}"/>
希望这对您有帮助。
关于WPF 组合框 Entity Framework 绑定(bind) (MVVM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17269021/