我正在實施mvvm模型。我有類調用Dep_Class在我的模型WPF MVVM綁定實體框架對Combobox的工作結果
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 = * database * '構造函數,並設置'DataContext = this;'。 –
好的,但你能解釋如何使用它沒有代碼隱藏plz? –
您應該在模型中創建medical_databaseEntitiescon對象。在模型中編寫一個方法返回_dbObj.branches。在viewModel中創建你的模型的一個實例。還要在視圖模型中創建一個List屬性,在getter中調用模型的_dbObj.branches方法。將此列表綁定到UI中的組合框。 –