wpf-ComboBox下拉菜单简单使用

问题描述

我有两个combobox,都需要以列表作为数据源,其中一个还涉及显示时的转换(后台是“+/-/ ”,前台则要显示“正向/反向/无方向”)。本篇涉及数据源的绑定和后台获取结果。

解决方案

前台

    <Window.Resources>
        <local:DirectionToZhConverter x:Key="dir2zh"/>
    </Window.Resources>

<!--这个需要转换-->
<ComboBox Grid.Row="4" Grid.Column="1" x:Name="gfDirection" SelectedIndex="0">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource dir2zh}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<!--这个不用转换-->
<ComboBox Grid.Row="5" Grid.Column="1" x:Name="gfType" SelectedIndex="0"/>

其中SelectedIndex是指默认选择的选项的index。

后台

public GraphFeatureWindow()
{
    
    
    InitializeComponent();
    List<string> directions = new List<string>{
    
    "+", "-", ""};
    List<string> types = new List<string> {
    
     "promoter", "primer_bind"};
    this.gfDirection.ItemsSource = directions;
    this.gfType.ItemsSource = types;
}
private void Submit_Click(object sender, RoutedEventArgs e)
{
    
    
    string dire_select = Convert.ToString(this.gfDirection.SelectedItem); # 获取值
    string type_select = Convert.ToString(this.gfType.SelectedItem);
    MessageBox.Show("*Direction:" + dire_select + "#Type:" + type_select + "&Name:" + gfi.Name);
}

转换器

	/// <summary>
	/// 把DisplayFeatureObject.direction转换成汉字
	/// </summary>
	public class DirectionToZhConverter : IValueConverter
	{
    
    
		object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
    
    
			string d = System.Convert.ToString(value);
			if (d == "+")
			{
    
    
				return "正向";
			}
			else if (d == "-")
			{
    
    
				return "反向";
			} else {
    
     
				return "无方向";
			}
		}

		object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
    
    
			string d = System.Convert.ToString(value);
			if (d == "正向")
			{
    
    
				return "+";
			}
			else if (d == "反向")
			{
    
    
				return "-";
			}
			else {
    
    
				return "";
			}
		}
	}

结果就是点击按钮,会弹出消息:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/pxy7896/article/details/118188335
今日推荐