【问题标题】:Load comboBox with enum`s - UWP and MVVM [closed]使用枚举加载组合框 - UWP 和 MVVM [关闭]
【发布时间】:2025-12-25 06:00:10
【问题描述】:

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

【问题讨论】:

  • 我投票结束这个问题,因为这不是一个问题

标签: c# xaml mvvm uwp


【解决方案1】:

好的

我已经引入了使用枚举加载 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”视图后面输入代码并添加一个方法,该方法将枚举加载到组合框中,并在构造函数中调用它:

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

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

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

享受吧!!!!

【讨论】: