wpf-ComboBox下拉菜单简单使用

本文介绍了一个WPF应用中使用ComboBox进行数据绑定和转换的实例。通过前台XAML设置DataTemplate和Converter,实现了后台数据显示为“正向/反向/无方向”的转换。在后台,利用List初始化数据源,并展示了如何获取选中项的值。点击按钮后,弹出的消息框显示了选择的值。
摘要由CSDN通过智能技术生成

问题描述

我有两个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 "";
			}
		}
	}

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值