【发布时间】:2017-06-13 02:34:47
【问题描述】:
我正在实现一个 mvvm 模型。我的模型中有一个名为 Dep_Class 的类
using System.ComponentModel;
namespace mency.Models
{
class Dep_class : INotifyPropertyChanged
{
private string dep_name;
public string Dep_Name
{
get { return dep_name; }
set
{
dep_name = value;
OnPropertyChanged("Dep_Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public Dep_class()
{
}
private void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
我通过 EntityFramework 连接了数据库,这是从 EF 生成的类
namespace mency
{
using System;
using System.Collections.Generic;
public partial class branch
{
public int Branch_ID { get; set; }
public string Branch_Name { get; set; }
}
}
在我的页面代码上我有 XAML
<Page x:Name="Departments_page" x:Class="mency.Department"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:mency"
xmlns:m="clr-namespace:mency.Models"
mc:Ignorable="d"
d:DesignHeight="502" d:DesignWidth="722"
Title="Department" Initialized="Departments_page_Initialized" Loaded="Departments_page_Loaded">
<Page.Resources>
<m:Dep_class x:Key="dep_class" />
</Page.Resources>
<Grid Background="MediumAquamarine">
<ComboBox x:Name="Branch_cbox" ItemsSource="{StaticResource dep_class}" />
</Grid>
如何将组合框绑定到我的数据库的加载结果。 这是我在页面后面的代码:
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace mency
{
/// <summary>
/// Interaction logic for Department.xaml
/// </summary>
public partial class Department : Page
{
medical_databaseEntitiescon _dbObj;
public Department()
{
InitializeComponent();
}
private void Departments_page_Initialized(object sender, EventArgs e)
{
}
private void Departments_page_Loaded(object sender, RoutedEventArgs e)
{
_dbObj = new medical_databaseEntitiescon();
//ComboBox = _dbObj.branches.ToList(); // I want combobox loaded with the results of this List
}
}
}
很抱歉问了这么长的问题,但我希望有人帮助我
【问题讨论】:
-
如果你想实现 MVVM,我建议不要使用代码隐藏。 MVVM 字面意思是 Model-View-ViewModel,使用后面的代码是针对该框架的。至于链接,如果你真的想使用代码隐藏,不要在你的xaml中设置
ItemSource={Binding ...,而是在Department()构造函数中使用Branch_cbox.ItemsSource = *list from database*,同时设置DataContext = this;。 -
好的,但是你能解释一下如何在没有代码隐藏的情况下使用它吗?
-
您应该在模型中创建 medical_databaseEntitiescon 对象。在模型中编写一个返回 _dbObj.branches 的方法。在 viewModel 中创建模型的实例。还要在视图模型中创建一个 List
属性,在 getter 中调用模型的 _dbObj.branches 方法。将此 List 绑定到 UI 中的组合框。
标签: c# wpf entity-framework mvvm combobox