简体   繁体   中英

Bind enum into ViewModel using C# WPF

I have an enum class where it has few statuses. I want to bind my enum to the combobox and once the save button is click it should save into the database by using mvvm pattern. For now, i am able to populate the enum statuses into the combobox, but can i bind it to the view model? And how can i save into the database from the enum.

Here is the xaml code:

 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>

And this is the error message I am getting now:

System.Windows.Data Error: 40 : BindingExpression path error: 'ProductionLineStatus' property not found on 'object' ''Status' (HashCode=0)'. BindingExpression:Path=ProductionLineStatus; DataItem='Status' (HashCode=0); target element is 'ComboBox' (Name='combobox_status'); target property is 'NoTarget' (type 'Object')

Here is the viewmode:

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));
        }
    }

}

Here is the model code:

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));
        }
    }
}

This helped to solve my problem

<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 ProductionLineConfigs.ProductionLineStatus, Converter={StaticResource statusToBooleanConverter}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM