简体   繁体   中英

Is it possible to add a default ComboBox entry with command binding in XAML?

I'm working on my first true WPF MVVM pattern application.

Currently I have a number of ComboBoxes on various screens that are bound to Collection classes and properties of the relevant ViewModel class.

They always have an entry with the text <Add> , which is really an empty object class and I currently use it to trigger an AddNewObject event if the Property bound to the SelectedItem has <Add> in its ToString() output. This strikes me as cumbersome and it ties the View too closely to the View model for my liking. eg

<ComboBox ItemsSource="{Binding AllObjects}" SelectedItem="{Binding SelectedObject}" />

then in ViewModel code:

  public SomeObjectType SelectedObject
  {
    get{return this.fieldSomeObjectType;}
    set
    {
      if(null==value)
        return;
      if(value.ToString().Contains(@"<Add>"))
      {
        if(null!=this.AddNewObject)
        {
          this.AddNewObject;
        }
      }
    }
 }

Is there a way in XAML of adding this extra line into the ComboBox drop down list and binding it to an AddNewObject Command?

The code you've written in your view has nothing to do with your business logic. Its fine. MVVM doesn't say that you shouldn't have anything in the codebehind of the view. Showing 'Add' is a requirement on the view and can be handled by the code behind of view.

In ASP.NET I've been doing this that I databinded the list control to some data but also specified some items in the html and it would merge them. Have you tried that?

use CompositeCollection for merging a default item with a itemsource. http://msdn.microsoft.com/en-us/library/ms742405.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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