У меня есть класс enum, где у него мало статусов. Я хочу привязать мое перечисление к комбинированному списку, и после нажатия кнопки «Сохранить» оно должно быть сохранено в базе данных с использованием шаблона mvvm. На данный момент я могу заполнить статусы перечислений в поле со списком, но могу ли я связать его с моделью представления? И как я могу сохранить в базу данных из перечисления.
Вот код xaml:
xmlns:enum="clr-namespace:application.Enum"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="Home" Height="450" Width="700">
<Window.DataContext>
<vm:ProductionLineConfigViewModel/>
</Window.DataContext>
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="enum:Status"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox x:Name="combobox_status" Grid.Column="2" Grid.Row="3" Margin="5.8,41.8,43.8,0" VerticalAlignment="Top" SelectionChanged="combobox_status_SelectionChanged"
ItemsSource="{Binding Source={StaticResource dataFromEnum}}" SelectedItem="{Binding ProductionLineStatus}" SelectedValue="{Binding ProductionLineStatus, Mode=TwoWay}" SelectedValuePath="ProductionLineStatus"/>
<Button Grid.Column="1" Grid.Row="5" Content="Back" Margin="24.8,7,24.8,42.6" x:Name="btnBack" Click="btnBack_Click"/>
<Button Grid.Column="2" Grid.Row="5" Content="Create" Margin="24.8,7,24.8,42.6" x:Name="btnCreate" Click="btnCreate_Click" Command="{Binding NewProductionLineConfigCommand}"/>
</Grid>
И это сообщение об ошибке, которое я получаю сейчас:
Ошибка System.Windows.Data: 40: Ошибка пути BindingExpression:
Свойство 'ProductionLineStatus' не найдено в 'объекте' '' Статус '
(HashCode = 0). BindingExpression: Path = ProductionLineStatus;
DataItem = 'Status' (HashCode = 0); целевой элемент - «ComboBox»
(Имя = 'combobox_status'); Свойство target - NoTarget (тип
'Объект')
Вот режим просмотра:
public class ProductionLineConfigViewModel : INotifyPropertyChanged
{
Database db = new Database();
MySqlDataReader reader;
MySqlDataAdapter da;
DataTable dt = new DataTable();
private ProductionLineConfig productionlineconfig;
public ProductionLineConfig ProductionLineConfigs
{
get { return productionlineconfig; }
set
{
productionlineconfig = value;
OnPropertyChanged("ProductionLineConfigs");
}
}
// TODO - List all productionline configs; Implement observablecollections
public List<ProductionLineConfig> listAllProductionLineConfigs
{
get
{
var plc = new List<ProductionLineConfig>();
string query;
query = "select * from productionlineconfig";
da = new MySqlDataAdapter(query, db.GetConnection());
da.Fill(dt);
reader = db.QueryCommand(query);
while (reader.Read())
{
plc.Add(new ProductionLineConfig()
{
ProductionLineId = Int32.Parse(reader[0].ToString()),
ProductLineCode = reader[1].ToString(),
ProductionLineName = reader[2].ToString(),
ProductionLineStatus = Convert.ToBoolean(reader[3].ToString()),
ProductionLineCreatedDate = Convert.ToDateTime(reader[4].ToString())
});
}
reader.Close();
return plc;
}
}
// TODO - Create new productionline config;
public void createNewProductionLineConfig()
{
string query;
try
{
query = "Insert into productionlineconfig (PRODUCTION_LINE_CODE, PRODUCTION_LINE_NAME, PRODUCTION_LINE_STATUS) Values ('" + ProductionLineConfigs.ProductLineCode + "' , '" + ProductionLineConfigs.ProductionLineName + "' , '" + ProductionLineConfigs.ProductionLineStatus + "')";
db.QueryCommand(query);
Console.WriteLine("User created successfully");
production_line_config plcWindow = new production_line_config();
plcWindow.Hide();
npi_home npiWindow = new npi_home();
npiWindow.Show();
}
catch (MySqlException ex)
{
Console.WriteLine(ex.ToString());
}
}
public NewProductionLineConfigCommand newProductionLineConfigCommand { get; set; }
public ProductionLineConfigViewModel()
{
ProductionLineConfigs = new ProductionLineConfig();
newProductionLineConfigCommand = new NewProductionLineConfigCommand(this);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Вот код модели:
public class ProductionLineConfig : INotifyPropertyChanged
{
private int id;
public int ProductionLineId
{
get { return id; }
set
{
id = value;
OnPropertyChanged("ProductionLineId");
}
}
private string linecode;
public string ProductLineCode
{
get { return linecode; }
set
{
linecode = value;
OnPropertyChanged("ProductLineCode");
}
}
private string linename;
public string ProductionLineName
{
get { return linename; }
set
{
linename = value;
OnPropertyChanged("ProductionLineName");
}
}
private bool status;
public bool ProductionLineStatus
{
get { return status; }
set
{
status = value;
OnPropertyChanged("ProductionLineStatus");
}
}
private DateTime createddate;
public DateTime ProductionLineCreatedDate
{
get { return createddate; }
set
{
createddate = value;
OnPropertyChanged("ProductionLineCreatedDate");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}