How can I convert Comboboxitem into string?

c00012 746 Reputation points
2021-05-21T12:49:08.57+00:00

Hello,

I have a combobox with enum source. I want to show selected combobox item in messagebox using MVVM and WPF.
Here's a code :

enum:

public enum ProdCode  
{  
    [Description("PersonalLoan")]  
    PersonalLoan,  
    [Description("Mortgage")]  
    Mortgage,  
    [Description("AutoLoan")]  
    AutoLoan  
};   

ICommand Interface:

   using System;  

using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApp6.ViewModel
{
class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;

    private Action<ComboBoxItem>_execute;  

    public MyCommand(Action<ComboBoxItem> execute)  
    {  
        _execute=execute;  
    }  
      
    public bool CanExecute(object parameter)=>true;  

    public void Execute(object parameter)  
    {  
        var value= parameter as ComboBoxItem;  
        _execute.Invoke(value);  
    }  
}  

}

ViewModel:

   using System.Windows.Controls;  

using System.Windows.Input;

namespace WpfApp6.ViewModel
{
class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

    public ICommand ProdNavCommand { get; set; }  

    //private Enum _selectedItem;  
    private ComboBoxItem _selectedItem;  
    public ComboBoxItem SelectedItem  
    {  
        get=>_selectedItem;  
        set  
        {  
            _selectedItem= value;  
            OnPropertyChanged(nameof(SelectedItem));  
        }  
    }  

    private void OnPropertyChanged(string propertyName)  
    {  
        if(PropertyChanged!=null)  
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
    }  

    public MyViewModel()  
    {  
        ProdNavCommand=new MyCommand((SelectedItem)=>MessageBox.Show(string.Format("You select:" + SelectedItem),"Goes to..."));  
    }  
}  

}
Result of above code:
98608-ice-screenshot-20210518-160914.png

I tried to fix error but I couldn't even the cause of it. somebody give me an advice, I would be very appreciated.

thanks,

c00012

Developer technologies | Windows Presentation Foundation
{count} votes

Answer accepted by question author
  1. Peter Fleischer (former MVP) 19,341 Reputation points
    2021-05-21T15:38:53.293+00:00

    Hi,
    try following demo based on your code::

    XAML:

    <Window x:Class="WpfApp1.Window063"  
            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:WpfApp063"  
            xmlns:sys="clr-namespace:System;assembly=mscorlib"  
            mc:Ignorable="d"  
            Title="Window063" Height="450" Width="800">  
      <Window.DataContext>  
        <local:MyViewModel/>  
      </Window.DataContext>  
      <Window.Resources>  
        <ObjectDataProvider x:Key="Codes"   
                            MethodName="GetValues"   
                            ObjectType="{x:Type sys:Enum}">  
          <ObjectDataProvider.MethodParameters>  
            <x:Type TypeName="local:ProdCode"/>  
          </ObjectDataProvider.MethodParameters>  
        </ObjectDataProvider>  
        </Window.Resources>  
        <StackPanel>  
        <ComboBox ItemsSource="{Binding Source={StaticResource Codes}}"  
                  SelectedItem="{Binding SelectedItem}"/>  
        <Button Command="{Binding ProdNavCommand}" Content="Check"/>  
      </StackPanel>  
    </Window>  
    

    And code:

    using System;  
    using System.ComponentModel;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Input;  
    
    namespace WpfApp063  
    {  
      public class MyViewModel : INotifyPropertyChanged  
      {  
        public event PropertyChangedEventHandler PropertyChanged;  
        public ICommand ProdNavCommand { get; set; }  
        public ProdCode SelectedItem { get; set; }  
        private void OnPropertyChanged(string propertyName) =>  
           PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        public MyViewModel()  
        {  
          ProdNavCommand = new MyCommand((state) => MessageBox.Show(string.Format("You select: " + SelectedItem), "Goes to..."));  
        }  
      }  
    
      public enum ProdCode  
      {  
        [Description("PersonalLoan")]  
        PersonalLoan,  
        [Description("Mortgage")]  
        Mortgage,  
        [Description("AutoLoan")]  
        AutoLoan  
      }  
    
      class MyCommand : ICommand  
      {  
        public event EventHandler CanExecuteChanged;  
        private Action<ComboBoxItem> _execute;  
        public MyCommand(Action<ComboBoxItem> execute) => _execute = execute;  
        public bool CanExecute(object parameter) => true;  
        public void Execute(object parameter)  
        {  
          var value = parameter as ComboBoxItem;  
          _execute.Invoke(value);  
        }  
      }  
    }  
    

    Result:

    ![98650-x.gif]1

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. DaisyTian-1203 11,651 Reputation points Moderator
    2021-05-24T02:20:54.78+00:00

    You need update two places for your MyViewModel
    1. Replace your ComboBoxItem SelectedItem with ProdCode SelectedItem like below:

     private ProdCode _selectedItem;  
            public ProdCode SelectedItem  
            {  
                get => _selectedItem;  
                set  
                {  
                    _selectedItem = value;  
                    OnPropertyChanged(nameof(SelectedItem));  
                }  
            }  
    

    2. Replace the contents of the constructor as:

    ProdNavCommand = new MyCommand((x) => MessageBox.Show(string.Format("You select:" + SelectedItem), "Goes to..."));  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.