繁体   English   中英

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

[英]Bind enum into ViewModel using C# WPF

我有一个枚举类,它的状态很少。 我想将我的枚举绑定到组合框,一旦单击保存按钮,它应该使用 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 路径错误:在“对象”“状态”(HashCode=0)上找不到“ProductionLineStatus”属性。 BindingExpression:Path=ProductionLineStatus; 数据项='状态'(哈希码=0); 目标元素是 'ComboBox' (Name='combobox_status'); 目标属性是“NoTarget”(类型“Object”)

这是视图模式:

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

这有助于解决我的问题

<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}}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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