简体   繁体   English

如何修改 Combobox 的选定文本?

[英]How I can modify the Selected text of Combobox?

I'm newer to C# for UI WPF and I would like to set the value of Combobox ?我对 UI WPF 的 C# 较新,我想设置Combobox的值?

cbx1.SelectedItem = "test 1";

This line show me every time null ( not an exception ) but the selectedItem is empty.这条线每次都向我显示 null (不是例外),但selectedItem是空的。

<telerik:RadComboBox Background="White" Foreground="{DynamicResource TitleBrush}"  x:Name="cbx1" AllowMultipleSelection="True" VerticalAlignment="Center" HorizontalAlignment="Right" Width="200" Grid.Row="1" Grid.Column="0" Margin="0,14,11,14" Height="22"/>

Update:更新:

I think that my question is not clear, I will give an example:我觉得我的问题不清楚,我举个例子:

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.Collections.ObjectModel;
namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ObservableCollection<Person> myPersonList = new ObservableCollection<Person>();

            Person personJobs = new Person("Steve", "Jobs");
            Person personGates = new Person("Bill", "Gates");

            myPersonList.Add(personJobs);

            myPersonList.Add(personGates);

            MyComboBox.ItemsSource = myPersonList;

            MyComboBox.SelectedItem = personGates;
        }
    }

    public class Person
    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            FirstName = firstName;
            LastName = lastName;
        }
    }
}

In this code, if myCombobox.displayMemberPath = FirstName , How can I set the selected FirstName???在这段代码中,如果myCombobox.displayMemberPath = FirstName ,我该如何设置选择的 FirstName ???

I do not have Teleriks Combobox, so I am using the standard Combobox here.我没有 Teleriks Combobox,所以我在这里使用标准的 Combobox。 You should also know that XAML is very quiet, it do not throw an exception, but you will probably find an error message in the Output window.你也应该知道 XAML 很安静,它不会抛出异常,但是你可能会在 Output window 中发现错误信息。

This example is following the MVVM pattern.此示例遵循 MVVM 模式。 This means that you will find most of the code in the PersonViewModel class (the "View Model") where the properties are bound to the View.这意味着您会在属性绑定到视图的 PersonViewModel class(“视图模型”)中找到大部分代码。 (I am not using the Model here, but that could be a data source class). (我在这里没有使用 Model,但这可能是一个数据源类)。 The PersonViewModel is inheriting the VMBase where the that notifies the View about changes in properties. PersonViewModel 继承了 VMBase,它通知 View 属性的变化。

So, to your problem: I have added a property "SelectedPerson".因此,对于您的问题:我添加了一个属性“SelectedPerson”。 This property is bound to the SelectedItem in the control.此属性绑定到控件中的 SelectedItem。 So each time you change the item in the combobox the SelectedPerson will contain the selected Person object.因此,每次更改 combobox 中的项目时,SelectedPerson 将包含选定的 Person object。

I have also added a button "Select Steve" that will, In the PersonViewModel, find the Person object with firstname = "Steve" and set the SelectedPerson to that object.我还添加了一个“选择史蒂夫”按钮,它将在 PersonViewModel 中找到名字为“史蒂夫”的人 object 并将 SelectedPerson 设置为该 object。 The Combobox will change to "Steve". Combobox 将更改为“史蒂夫”。

Window1.xaml Window1.xaml

  <Window x:Class="SO65149368.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SO65149368"
        mc:Ignorable="d"
        Title="Window1" Height="450" Width="800">
    <StackPanel>
        <ComboBox Name="MyComboBox" Width="300" HorizontalAlignment="Left" Margin="5"
                  ItemsSource="{Binding myPersonList}"
                  DisplayMemberPath="FirstName"
                  SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"/>
        <StackPanel Orientation="Horizontal">
            <Button x:Name="SelectSteve" Content="Select Steve" Click="SelectSteve_Click" 
   Margin="5"/>
        </StackPanel>
    </StackPanel>
  </Window>

Window1.xaml.cs Window1.xaml.cs

using System.Windows;

namespace SO65149368
{
    public partial class Window1 : Window
    {
        public PersonViewModel PersonViewModel = new PersonViewModel();
        public Window1()
        {
            DataContext = PersonViewModel;
            InitializeComponent();
        }

        private void SelectSteve_Click(object sender, RoutedEventArgs e)
        {
            PersonViewModel.SelectSteve();
        }
    }
}

PersonViewModel.cs PersonViewModel.cs

using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;

namespace SO65149368
{
    public class PersonViewModel : VMBase
    {
        public ObservableCollection<Person> myPersonList { get; } = new ObservableCollection<Person>();
        public PersonViewModel()
        {
            Person personJobs = new Person("Steve", "Jobs");
            Person personGates = new Person("Bill", "Gates");

            myPersonList.Add(personJobs);
            myPersonList.Add(personGates);

            SelectedPerson = personGates;
            //MyComboBox.ItemsSource = myPersonList;
            //MyComboBox.SelectedItem = personGates;
        }

        public Person SelectedPerson
        {
            get { return _selectedPerson; }
            set 
            {
                Set(ref _selectedPerson, value);
                Debug.WriteLine("Selected person: " + SelectedPerson.FirstName + " " + SelectedPerson.LastName);
            }
        }
        private Person _selectedPerson;

        public void SelectSteve()
        {
            SelectedPerson = myPersonList.FirstOrDefault(p => p.FirstName == "Steve");
        }
    }
}

VMBase.cs VMBase.cs

using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace SO65149368
{
    public abstract class VMBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected bool Set<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
        {
            if (!EqualityComparer<T>.Default.Equals(field, newValue))
            {
                field = newValue;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
                return true;
            }

            return false;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM