将组合框选择的项目作为方法参数传递 [英] Pass ComboBox Selected Item as Method Parameter

查看:120
本文介绍了将组合框选择的项目作为方法参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将ComboBox选定项作为方法参数传递的正确方法是什么?

What's the proper way to pass a ComboBox Selected Item as a Method Parameter?

还是这样做有什么好处?

Or is there even any advantage to doing this?

我在程序设计和传递参数方面经验有限.

I have limited experience in program design and passing parameters.

这是一个示例方法,它返回选定对象的相反颜色.

Here's an example method that returns the opposite color of selected.

<ComboBox x:Name="cboColors" 
          HorizontalAlignment="Left" 
          Margin="179,82,0,0" 
          VerticalAlignment="Top"
          Width="120"
          SelectedIndex="0">
    <System:String>Red</System:String>
    <System:String>Orange</System:String>
    <System:String>Yellow</System:String>
    <System:String>Green</System:String>
    <System:String>Blue</System:String>
    <System:String>Purple</System:String>
</ComboBox>


C夏普

硬编码


C Sharp

Hardcoded

ComboBox Selected Item在if语句中设置

ComboBox Selected Item is set in the if statement

// Find Opposite Color
//
public String OppositeColor()
{
    if ((string)cboColors.SelectedItem == "Red")
    {
        return "Green";
    }
    else if ((string)cboColors.SelectedItem == "Orange")
    {
        return "Blue";
    }
    else if ((string)cboColors.SelectedItem == "Yellow")
    {
        return "Purple";
    }
    else if ((string)cboColors.SelectedItem == "Green")
    {
        return "Red";
    }
    else if ((string)cboColors.SelectedItem == "Blue")
    {
        return "Orange";
    }
    else if ((string)cboColors.SelectedItem == "Purple")
    {
        return "Yellow";
    }
    else
    {
        return string.Empty;
    }
}


// Display Opposite Color Button
//
private void button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show(OppositeColor());
}

 

传递参数

将组合框选定项"设置为一个对象,然后传递给方法

ComboBox Selected Item is set to an Object then passed to the Method

// Find Opposite Color
//
public String OppositeColor(Object color)
{
    if (color.Equals("Red"))
    {
        return "Green";
    }

    ...
}


// Display Opposite Color Button
//    
private void button_Click(object sender, RoutedEventArgs e)
{
    // Set Selected Color
    Object color = cboColors.SelectedItem;

    // Display
    MessageBox.Show(OppositeColor(color));
}

推荐答案

WPF具有可以帮助您解决此问题的绑定. 如果您创建一个简单的帮助器类来表示组合框中的项目,则:

WPF has bindings that can help you with this. If you create a simple helper class to represent your items in the combobox:

public class ComboItem
{
  public string Color { get; private set; }
  public string OppositeColor { get; private set; }

  public ComboItem(string color, string opposite)
  {
    Color = color;
    OppositeColor = opposite;
  }
}

并且在您后面的代码中有一个组合框可以绑定到的集合:

And in your code behind have a collection the combobox can bind to:

private List<ComboItem> _myComboItems = new List<ComboItem>()
{
  new ComboItem("Red", "Green"),
  new ComboItem("Orange", "Blue"),
  new ComboItem("Yellow", "Purple"),
  new ComboItem("Green", "Red"),
  new ComboItem("Blue", "Orange"),
  new ComboItem("Purple", "Yellow")
};

public List<ComboItem> MyComboItems
{
  get { return _myComboItems; }
}

在视图中的属性发生更改时(无需实现和依赖属性),对事件实施UI的INotifyPropertyChanged接口:

Implement INotifyPropertyChanged interface to event to the UI when a property in your view changes (without having to implement and dependency properties):

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

以及用户进行选择时要设置的项目:

And an item to set when the user makes a selection:

private ComboItem _selected = null;

public ComboItem SelectedComboItem
{ 
  get { return _selected; }
  set
  {
    _selected = value;
    OnPropertyChanged("SelectedComboItem");
  }
}

您可以将xaml设置为:

you are able to set your xaml to look like:

<ComboBox ItemsSource="{Binding MyComboItems}"
          SelectedItem="{Binding SelectedComboItem}"
          DisplayMemberPath="Color"/>

此操作就位,当用户按下按钮(button1)时,您的处理程序可以通过几种不同的方式完成您想要的操作:

Ince this is in place, when the user presses the button (button1), your handler can do what you want it to in a few different ways:

private void button_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show(SelectedComboItem.OppositeColor);
}

直接访问相反颜色或要传递参数的选定项属性:

which accesses the selected items property for opposite color directly, or for your want to pass parameters:

private void button_Click(object sender, RoutedEventArgs e)
{
  MessageBox.Show(GetOppositeColor(SelectedComboItem));
}

private string GetOppositeColor(ComboItem item)
{
  if (item != null)
    return item.OppositeColor;

  return "No opposite color available";
}

要在组合中设置初始选定的项目,请执行以下操作:

To set the initial selected item in the combo:

InitializeComponent();
// some other initialization code here...
SelectedComboItem = MyComboItems[0];

此属性SelectedComboItem的设置将导致PropertyChanged事件(通过OnPropertyChanged触发),组合框将获取并调整其选定的项目.

This setting of the property SelectedComboItem will cause the PropertyChanged event to fire (through OnPropertyChanged) which the combobo will get and adjust its selected item.

IMO保持类型对于可读性和效率很重要.将值更改为Object类型,然后强制转换为它的特定类型,或者使用ToString()效率不如将其保持为始终以其开头并访问其值的类型,而且在键入时也使得遵循代码更加困难变形为对象然后再次返回.

IMO keeping the types is important for readability and efficiency. Changing an value to type Object then casting back to the specific type it is or using ToString() is less efficient than keeping it as the type it always was to begin with and accessing its value, and it also makes following the code harder when types morph to Object and back again.

我的代码示例消除了使用将字符串配对在一起的集合,而赞成使用类来包装关系.这使您能够利用WPF的魔力来获取用户交互事件(例如,选择组合中的一项),并自动(通过SelectedItem绑定)访问所选内容所代表的对象.

My code example eliminates the use of collections for pairing strings together in favor of using a class to wrap the relationship up. This enables you to utilize WPF's magic to get user interaction events (like selecting an item in a combo) and automatically having access to the object the selection represents (through the SelectedItem binding).

希望这会有所帮助.

这篇关于将组合框选择的项目作为方法参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆