我找到了一些主题"如何从枚举列表"中绑定组合框,但我的问题是我尝试使用MVVM arhitecture并让我的View(xaml)清晰如下所示:
View(xaml.cs)的一部分:
public partial class GreenCertificatesStockForm : Erp.Core.Wpf.BaseWindow
{
private Models.GreenCertificatesGroupModel model;
public GreenCertificatesStockForm()
{
model = new Models.GreenCertificatesGroupModel();
this.DataContext = model;
InitializeComponent();
model.LoadForm(); // propose some dates for my form
model.RequestClose += () => { Close(); };
}
}
部分视图(xaml)我的RadComboBox:
<telerik:RadComboBox Name="certificatesTypeRadComboBox"
Margin="5 2 0 2" Width="150"
SelectedValue="{Binding CertificatesTypeEnum , Mode=TwoWay,
ValidatesOnDataErrors=True,
ValidatesOnExceptions=True,
NotifyOnValidationError=True}"
ItemSource="{Binding }"
SelectedItem="{Binding }"
telerik:StyleManager.Theme="Office_Blue" BorderBrush="#FF707070" Background="#FFDDDDDD"
>
</telerik:RadComboBox>
所以,我的枚举列表是在 ViewModel(class.cs)中创建的:
public enum CertificatesTypeEnum {
Estimat = 1,
Calculat = 2,
Facturat = 3
}
我需要在我的RadComboBox中显示Enum的所有值和selectedValue以在DB中保存特定的选择键(带参数)。如何将ViewModel中的值显示到ComboBox(View)?
我知道可以做类似的事情:
var items = Enum.GetValues(typeof(CertificatesTypeEnum)).Cast<CertificatesTypeEnum>().Select(i => new ComboboxItem()
{ Text = Enum.GetName(typeof(gender), i), Value = (int)i}).ToArray<ComboboxItem>();
//Add the items to your combobox (given that it's called comboBox1)
RadComboBoxName.Items.AddRange(items);
但必须在xaml.cs文件中进行(我不想要这个解决方案),因为在ViewModel中,组合框无法识别,也无法找到。
简而言之:在xaml文件中显示来自ViewModel类的枚举列表值。
答案 0 :(得分:1)
为什么不在视图模型中调用Enum.GetValues
方法?这是MVVM:
public class GreenCertificatesGroupModel
{
public IEnumerable<CertificatesTypeEnum> EnumValues
{
get
{
var list = Enum.GetValues(typeof(CertificatesTypeEnum)).Cast<CertificatesTypeEnum>();
return list;
}
}
private CertificatesTypeEnum _selectedItem;
public CertificatesTypeEnum SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; }
}
}
<强> XAML:强>
<telerik:RadComboBox ItemsSource="{Binding EnumValues}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />