简体   繁体   English

是否可以在XAML中添加带有命令绑定的默认ComboBox条目?

[英]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. 我正在开发我的第一个真正的WPF MVVM模式应用程序。

Currently I have a number of ComboBoxes on various screens that are bound to Collection classes and properties of the relevant ViewModel class. 目前,我在各种屏幕上都有许多ComboBox,这些ComboBox绑定到Collection类和相关ViewModel类的属性。

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. 他们总是有一个带有文本<Add>的条目,这实际上是一个空的对象类,如果绑定到SelectedItem的Property在其ToString()输出中具有<Add> ,则我当前使用它来触发AddNewObject事件。 This strikes me as cumbersome and it ties the View too closely to the View model for my liking. 这给我带来了麻烦,并且将View与View模型联系得太紧密了(我喜欢)。 eg 例如

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

then in ViewModel code: 然后在ViewModel代码中:

  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? XAML中是否有一种方法可以将此多余的行添加到ComboBox下拉列表中,并将其绑定到AddNewObject命令?

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. MVVM并不表示视图的代码中不应包含任何内容。 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. 在ASP.NET中,我一直在执行以下操作:将列表控件数据绑定到一些数据,但同时在html中指定了一些项目,它将合并它们。 Have you tried that? 你有尝试过吗?

use CompositeCollection for merging a default item with a itemsource. 使用CompositeCollection将默认项目与itemsource合并。 http://msdn.microsoft.com/en-us/library/ms742405.aspx http://msdn.microsoft.com/en-us/library/ms742405.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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