Articles in this section
Category / Section

How to bind ComboBoxAdv in MVVM?

1 min read

To bind a ComboBox in MVVM pattern. The following code snippet will explain us how to bind the ComboBox in the MVVM pattern.

 

Model:

 

 

public class Model

{

     private string text;

     public string Text

     {

           get { return text; }

           set { text = value; }

     }

}

 

 

ViewModel:

 

 

public class ViewModel : INotifyPropertyChanged

{

   #region ICommand

    private ICommand _clickCommand;

    public ICommand ClickCommand

    {

       get

       {

        return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), () => CanExecute));

        }

    }

    public bool CanExecute

    {

       get

       {

          return true;

       }

     }

    #endregion

     public void MyAction()

     {

        SelectedModel = ModelItems[2];

     }

 

     private ObservableCollection<Model> modelItems;

 

     public ObservableCollection<Model> ModelItems

     {

        get { return modelItems; }

        set

        {

           modelItems = value;

        }

     }

 

       

    private Model selectedModel;

 

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyRaised(string propertyname)

    {

      if (PropertyChanged != null) { }

    }

 

    public Model SelectedModel

    {

       get { return selectedModel; }

       set { selectedModel = value; OnPropertyRaised("SelectedModel"); }

    }

 

    public ViewModel()

    {

      ModelItems = new ObservableCollection<Model>();

      SelectedModel = new Model();

      Model model1 = new Model() { Text = "Item1" };

      Model model2 = new Model() { Text = "Item2" };

      Model model3 = new Model() { Text = "Item3" };

 

      ModelItems.Add(model1);

      ModelItems.Add(model2);

      ModelItems.Add(model3);

    }

}

 

 

 

 

 

 

MainWindow.xaml:

 

 

<Grid>

    <syncfusion:ComboBoxAdv VerticalAlignment="Center" ItemsSource="{Binding ModelItems}" DisplayMemberPath="Text" SelectedItem="{Binding SelectedModel,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Center" Width="126">         

    </syncfusion:ComboBoxAdv>

</Grid>

 

 

 

MainWindow.xaml.cs:

 

 

public partial class MainWindow : Window

{

   public MainWindow()

   {

      InitializeComponent();

      this.DataContext = new ViewModel();

   }

}

 

 

Sample: ComboBoxMVVM

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied