加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:58:16 所属栏目:百科 来源:网络整理
导读:我的wpf应用程序中有一个静态ComboBox,加载空格后跟0-9.我有以下代码,这是我需要的工作,但我不觉得它是一个伟大的方式.任何建议或意见将不胜感激. Test.xaml ComboBox Name="cbImportance" Text="{Binding SelectedStory.ImportanceList,UpdateSourceTrigger
我的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;
}

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

>通过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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读