用枚举加载comboBox-UWP和MVVM

时间:2018-08-30 21:36:51

标签: c# xaml mvvm uwp

我如何在UWP中加载带有枚举的ComboBox并在C#中使用MVVM模型,他进行了搜索但找不到

1 个答案:

答案 0 :(得分:0)

Okey

我带来了使用枚举来加载comBox的过程...我花了很短的时间才发现它,但是我没有发现它

第一件事是在名为“ enums”的类中创建我们需要的枚举,该枚举将被称为“ TYPE_IDENTITY”:

using System.ComponentModel.DataAnnotations;
namespace Proyect.Model
{
    public enum TYPE_IDENTITY: byte {
        [Display (Name = "Nit")] NIT,
        [Display (Name = " Identification Card ")] IC,
        [Display (Name = " Foreign Identification Card ")] FIC,
        [Display (Name = "Passaport")] PASSAPORT,
        [Display (Name = "Other")] OTHER = 9
    }
}

现在,我们将在XAML页面上创建ComboBox,在本例中,该页面称为“ CombWithEnum.xaml”:

<ComboBox x: Name = "CobIdenti" Header = "Document Type" Width = "150" />

我们在“ CombWithEnum.xaml.cs”视图后面输入代码,并添加一个方法,该方法将枚举加载到comboBox中,并在构造函数中将其称为:

public CombWithEnum () // This is the contructor
{
    this.InitializeComponent();
    this.EnumsCombo(); 
}

public void EnumsCombo () // This is the method that will load the ComboBox
{
     var _enumval = Enum.GetValues​​(typeof (Proyect.Model.TYPE_IDENTITY)).Cast<Proyect.Model.TYPE_IDENTITY> ();
     var x = _enumval.ToList();
     CobIdenti.ItemsSource = x;
}

现在,如果我们想从comboBox的枚举中省略某些项目,我们添加:

x.Remove (Proyect.Model.TYPE_IDENTITY.FIC); // In this case I would omit "FIC" when loading the list

方法如下:

public void EnumsCombo ()
{
      var _enumval = Enum.GetValues ​​(typeof (Proyect.Model.TYPE_IDENTITY)).Cast<Proyect.Model.TYPE_IDENTITY> ();
      var x = _enumval.ToList();
      CobIdenti.ItemsSource = x;
}

如果需要,可以使用ComboBox中的MVVM来绑定ViewModel:

<ComboBox x:Name="CobIdenti" Header="Document Type" Width="150" SelectedValue="{Binding Type_Identity_Binding, Mode=TwoWay}"/>

在ViewModel中将保留该对象,以供类使用

 public class CombWithEnum : ViewModelBase
 {
      public TYPE_IDENTITY Type_Identity_Binding{get; set;}
 }

享受!!!