使用C#WPF将枚举绑定到ViewModel

时间:2018-09-12 07:24:28

标签: c# wpf enums

我有一个枚举类,其中的状态很少。我想将枚举绑定到组合框,单击“保存”按钮后,应使用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 ='状态'(HashCode = 0);目标元素是“ ComboBox”   (名称='combobox_status');目标属性为“ 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));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这有助于解决我的问题

account_following