我的wpf应用程序中有一个静态ComboBox,加载空格后跟0-9.我有以下代码,这是我需要的工作,但我不觉得它是一个伟大的方式.任何建议或意见将不胜感激.
Test.xaml
<ComboBox Name="cbImportance" Text="{Binding SelectedStory.ImportanceList,UpdateSourceTrigger=PropertyChanged,ValidatesOnExceptions=True,NotifyOnValidationError=True,ValidatesOnDataErrors=True}" Validation.ErrorTemplate="{StaticResource ErrorTemplate}" Loaded="cbImportance_Loaded" Grid.Column="1" d:LayoutOverrides="Height" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Margin="0,9" SelectionChanged="cbImportance_SelectionChanged" />
Test.xaml.cs
private void cbImportance_Loaded(object sender,RoutedEventArgs e) { List<string> data = new List<string>(); data.Add(""); data.Add("0"); data.Add("1"); data.Add("2"); data.Add("3"); data.Add("4"); data.Add("5"); data.Add("6"); data.Add("7"); data.Add("8"); data.Add("9"); // ... Get the ComboBox reference. var cbImportance = sender as ComboBox; // ... Assign the ItemsSource to the List. cbImportance.ItemsSource = data; // ... Make the first item selected. cbImportance.SelectedIndex = 0; }
>通过XAML(由Anatoliy Nikolaev建议)
> xaml.cs(Like Above)
>在viewmodel中创建构造函数并将静态值加载回ComboBox?
解决方法
在WPF中通过标记扩展支持XAML中的对象数组.这对应于x:ArrayExtension XAML类型
MSDN
.
你可以这样做:
<Window ... xmlns:sys="clr-namespace:System;assembly=mscorlib"> <x:Array x:Key="ParametersArray" Type="{x:Type sys:String}"> <sys:String>0</sys:String> <sys:String>1</sys:String> <sys:String>2</sys:String> <sys:String>3</sys:String> ... </x:Array> <ComboBox Name="ParameterComboBox" SelectedIndex="0" ItemsSource="{StaticResource ParametersArray}" ... />
要在x中设置空字符串:Array使用静态成员:
<x:Array x:Key="ParametersArray" Type="{x:Type sys:String}"> <x:Static Member="sys:String.Empty" /> <sys:String>0</sys:String> <sys:String>1</sys:String> <sys:String>2</sys:String> <sys:String>3</sys:String> ... </x:Array>
如果您需要定义带Int32类型的静态ComboBox,则可以更短:
<Window.Resources> <Int32Collection x:Key="Parameters">0,1,2,3,4,5,6,7,8,9</Int32Collection> </Window.Resources> <ComboBox Width="100" Height="30" ItemsSource="{StaticResource Parameters}" />
或者像这样:
<ComboBox Width="100" Height="30"> <ComboBox.ItemsSource> <Int32Collection>0,9</Int32Collection> </ComboBox.ItemsSource> </ComboBox>