C# · 12月 27, 2021

c# – 在WPF中执行静态ComboBox的方法

我的wpf应用程序中有一个静态Combo@R_980_2419@,加载空格后跟0-9.我有以下代码,这是我需要的工作,但我不觉得它是一个伟大的方式.任何建议或意见将不胜感激.

Test.xaml

<Combo@R_980_2419@ 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 Combo@R_980_2419@ reference. var cbImportance = sender as Combo@R_980_2419@; // … Assign the ItemsSource to the List. cbImportance.ItemsSource = data; // … Make the first item selected. cbImportance.SelectedIndex = 0;}

哪个是将静态值加载到Combo@R_980_2419@中的有效方法:

>通过XAML(由Anatoliy Nikolaev建议)
> xaml.cs(Like Above)
>在viewmodel中创建构造函数并将静态值加载回Combo@R_980_2419@?

解决方法 在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><Combo@R_980_2419@ Name=”ParameterCombo@R_980_2419@” 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类型的静态Combo@R_980_2419@,则可以更短:

<Window.Resources> <Int32Collection x:Key=”Parameters”>0,1,2,3,4,5,6,7,8,9</Int32Collection></Window.Resources><Combo@R_980_2419@ Width=”100″ Height=”30″ ItemsSource=”{StaticResource Parameters}” />

或者像这样:

<Combo@R_980_2419@ Width=”100″ Height=”30″> <Combo@R_980_2419@.ItemsSource> <Int32Collection>0,9</Int32Collection> </Combo@R_980_2419@.ItemsSource></Combo@R_980_2419@>