问题
Ok, this sounds trivial even to me, but I'm not able to find an answer to this.
I have a normal ComboBox
, which works perfectly.
What I would like to do is add an element
(as the last item of the drop-down list
) which is nothing but a Add new label
; when this item is selected, I want to open a window which allows me to define the properties of the element
I'm adding.
Right now I have the following:
<ComboBox x:Name="myCombo"
SelectedValue="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Definitions}"
SelectedValuePath="Name"
DisplayMemberPath="Name"
SelectionChanged="CheckToAdd" />
And the CheckToAdd
function is like this:
private void CheckToAdd(object sender, SelectionChangedEventArgs e)
{
if (((myViewModel)e.AddedItems[0]).Name.Value.Equals("Add new"))
{
AddNewItem(sender, null);
}
}
What I do is have a dummy element
in my Definitions
which has Add new as Name
. Using this approach makes all working, but it's ugly IMO (because the problem is just a view
thing, so I don't think it's correct to mess with the VM or the Model
).
Anyone has a better idea?
回答1:
There's no equivalent of ASP.NET's AppendDataBoundItems
for WPF. You may be able to get somewhere by modifying the ControlTemplate, or you could simplify your current approach tp make it more readable. Something like:
private void CheckToAdd(object sender, SelectionChangedEventArgs e) {
if (cbo.SelectedIndex == Definitions.Count()) {
AddNewItem(sender, null);
}
回答2:
I suppose this really belongs in a comment to the accepted answer, but I have insufficient rep.
Could you elaborate on:
- How to ensure
element
withname
"Add new" stays at the bottom. - How to wrap the
Collection
from the Model in the ViewModel while adding the dummy item.
回答3:
if u follow binding in wpf u have to inset item in collection(here Definitions) and make this collection notify(using INotifyPropertyChanged) then automatically your ComboBox is update when new item is inserted it's not only one way to do to this but it's best practices
see following link to that's defind how to implement INotifyPropertyChanged
http://wpftutorial.net/INotifyPropertyChanged.html
来源:https://stackoverflow.com/questions/14257656/add-add-new-item-to-combobox