【问题标题】:How I can modify the Selected text of Combobox?如何修改组合框的选定文本?
【发布时间】:2020-12-03 16:38:59
【问题描述】:

我对 UI WPF 的 C# 比较陌生,我想设置 Combobox 的值?

cbx1.SelectedItem = "test 1";

这一行每次都显示 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"/>

更新:

我觉得我的问题不清楚,我举个例子吧:

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;
        }
    }
}

在这段代码中,如果myCombobox.displayMemberPath = FirstName,如何设置选中的FirstName???

【问题讨论】:

    标签: c# wpf telerik


    【解决方案1】:

    我没有 Teleriks Combobox,所以我在这里使用标准的 Combobox。 您还应该知道 XAML 非常安静,它不会抛出异常,但您可能会在“输出”窗口中找到错误消息。

    此示例遵循 MVVM 模式。这意味着您将在 PersonViewModel 类(“视图模型”)中找到大部分代码,其中属性绑定到视图。 (我在这里没有使用模型,但这可能是一个数据源类)。 PersonViewModel 继承了 VMBase,它通知 View 属性的变化。

    所以,对于您的问题:我添加了一个属性“SelectedPerson”。此属性绑定到控件中的 SelectedItem。因此,每次更改组合框中的项目时,SelectedPerson 都会包含选定的 Person 对象。

    我还添加了一个“选择 Steve”按钮,它将在 PersonViewModel 中找到 firstname =“Steve”的 Person 对象并将 SelectedPerson 设置为该对象。组合框将变为“Steve”。

    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

    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

    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

    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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多