Search code examples
c#wpftelerik

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?

cbx1.SelectedItem = "test 1";

This line show me every time null ( not an exception ) but the selectedItem is empty.

<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???


Solution

  • I do not have Teleriks Combobox, so I am using the standard Combobox here. 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.

    This example is following the MVVM pattern. 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. (I am not using the Model here, but that could be a data source class). The PersonViewModel is inheriting the VMBase where the that notifies the View about changes in properties.

    So, to your problem: I have added a property "SelectedPerson". This property is bound to the SelectedItem in the control. So each time you change the item in the combobox the SelectedPerson will contain the selected 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. The Combobox will change to "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;
            }
        }
    }