如何从所选项目组合框控件中获取字符串值? [英] How to get string value from selected item combobox control ?

查看:68
本文介绍了如何从所选项目组合框控件中获取字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



如果有人能告诉我如何从组合框中的选定项目中检索字符串值,而组合框被绑定到对象集合,我将不胜感激(根据下面的代码示例)。



无论我如何尝试只获得结果我得到的是空值或ComboBoxSelectedItem.Person



我需要的只是一个简单的例子或只是解释我做错了什么。



提前谢谢。



这是我的cs代码:

Hi All,

I would appreciate if someone could tell me how can i retrieve string value from selected item in a combobox while combobox is binded to object collection (as per code example below).

No matter how i tried only results i get is either empty value or ComboBoxSelectedItem.Person

All i need is a simple example or just explanation what am i doing wrong.

Thank you in advance.

This is my cs code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace ComboBoxSelectionBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> oc;

        public MainWindow()
        {
            InitializeComponent();
            oc = new ObservableCollection<Person>();

            oc.Add(new Person { Username = "Username 1", Name = "name1", Surname = "surname1"});
            oc.Add(new Person { Username = "Username 2", Name = "name2", Surname = "surname2" });
            oc.Add(new Person { Username = "Username 3", Name = "name3", Surname = "surname3" });

            this.DataContext = oc;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(cbName.SelectedValue.ToString()  + " , "  + oc[0].SelectedUsername);
        }
    }

    public class Person : INotifyPropertyChanged 
    {
        private string username;
        private string name;
        private string surname;
        private string selectedUsername;

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public string Username
        {
            get { return this.username; }
            set { if (value != this.username) { this.username = value; NotifyPropertyChanged("Username"); } }
        }

        public string Name
        {
            get
            {
                return name;
            }

            set
            {
                if (value != name)
                {
                    name = value;
                    NotifyPropertyChanged("Name");
                }
            }
        }

        public string Surname
        {
            get
            {
                return surname;
            }

            set
            {
                if (value != surname)
                {
                    surname = value;
                    NotifyPropertyChanged("Surname");
                }
            }
        }

        public string SelectedUsername
        {
            get
            {
                return selectedUsername;
            }
            set
            {
                if (value != selectedUsername)
                {
                    this.selectedUsername = value;
                    NotifyPropertyChanged("SelectedUsername");
                }
            }
        }
    }

}





这是我的XAML:





And this my XAML:

<Window x:Class="ComboBoxSelectionBinding.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ComboBox Name="cbName" ItemsSource="{Binding}" DisplayMemberPath="Username" SelectedValue="{Binding SelectedUsername}"/>
        <Label DataContext="{Binding ElementName=cbName,Path=SelectedItem}" Content="{Binding Name}"/>
        <Label DataContext="{Binding ElementName=cbName, Path=SelectedItem}" Content="{Binding Surname}"/>
        <Button Content="Show Selected Member" Height="23" Name="button1" Width="Auto" Click="button1_Click" />
    </StackPanel>
</Window>

推荐答案

首先,我强烈建议删除成员 SelectedUsername 。这是一种颠倒的设计,也违反了单点真相的基本原则。 (我不能提到不要重复自己),因为你是在重复,但不是你自己,而是已经存在的功能。它也违反了自然组合语义。



相反,处理组合框外的选定对象。属性 SelectedUsername instance property!,在语义上,与类的任何特定实例无关。它真的属于组合框,没有别的。严格来说,它可能是从 ComboBox 派生的类的属性,但这会很简单,更简单,你可以得到选定的对象:

First of all, I would strongly recommend to remove the member SelectedUsername at all. This is an upside-down design and also the violation of the very basic principle "Single Point of Truth". (I cannot refer to "Don't Repeat Yourself"), because you are repeating, but not yourself, but already existing functionality. It also violates natural composition semantics.

Instead, handle selected object outside of the combo box. The property SelectedUsername (instance property!, semantically, has nothing to do with any of the particular instances of the class Person. It really belongs to the combo box, nothing else. Strictly speaking, it could be a property of the class derived from ComboBox, but this would be a great overkill. Much simpler, you can just get the selected object:
Person selectedPerson = (Person)myComboBox.SelectedItem;
// always successful type cast,
// it you populate it only with Person instances



是的,就这么简单。



您的代码中还有另一个(潜在?)问题。我强烈建议您覆盖 System.Object.ToString() Person 类中。要返回什么?无论你想在屏幕上显示什么e item,当该类的实例被添加到列表框,组合框等中时。可以是名称姓氏用户名,任意组合他们以某种形式,无论你想要什么。我无法看到你在XAML中关注这个字符串的位置,所以这个易于编写的覆盖函数在这个和许多其他情况下都很方便。



见另外:

http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox%28v=vs.110%29.aspx [ ^ ],

http: //msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem%28v=vs.110%29.aspx [ ^ ],

http://en.wikipedia.org/wiki/Single_Point_of_Truth [ ^ ],

http:// en .wikipedia.org / wiki / Don%27t_repeat_yourself [ ^ ]。





-SA


Yes, as simple as that.

There is another (potential?) problem in your code. I would strongly advise you to override System.Object.ToString() in your Person class. What to return? Whatever you want to show on screen in the item, when the instance of this class is added to a list box, combo box, and the like. Could be a Name, Surname, Username, any combination of them in some format, whatever you want. I cannot see where you take care about this string in your XAML, so this easy-to-write overridden function could be handy in this and many other cases.

See also:
http://msdn.microsoft.com/en-us/library/system.windows.controls.combobox%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem%28v=vs.110%29.aspx[^],
http://en.wikipedia.org/wiki/Single_Point_of_Truth[^],
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^].


—SA


这篇关于如何从所选项目组合框控件中获取字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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