Editable WPF ListBox

I have an ObservableCollection related to a ListBox in WPF. I want the ListBox to be editable, and that the editing changes be saved in the collection. Since WPF does not provide an editable list, I tried to create my own by modifying ListBox.ItemTemplate.

<ListBox.ItemTemplate>
    <DataTemplate>                      
        <TextBox Name="EditableText" Text="{TemplateBinding Content}"/>
    </DataTemplate>
</ListBox.ItemTemplate>

Changing the ItemTemplate gives me editable fields, but any changes to the text fields are not saved in the ObservableCollection. Is there a way to have an editable two-way ListBox?

+5
source share
2 answers

You cannot do it this way.

, , " ", , .

, :

class ListBox
{
  Bind(Items)
  {
    foreach(var item in Items)
    {
      DataTemplate Template = LoadTemplateForItem(item.GetType()); // this is where your template get loaded
      Template.Bind(item); //this is where your template gets bound
    }
  }
}

(DataTemplate ) , ( , ) . . , , , . , TextBox. , "" . , . , ( , ).

, , , , :

public class MyDataItem
{
  string Data { get; set;}
}

ListBox :

<ListBox.ItemTemplate>
    <DataTemplate>                                              
            <TextBox Name="EditableText" Text="{Binding Data, Mode=TwoWay}"/>
    </DataTemplate>
</ListBox.ItemTemplate>
+8

, , , Content. :

// model class
public class Widget : INotifyPropertyChanged
{
  public string Description { ... }
}

<!-- view -->
<DataTemplate>
  <TextBox Text="{Binding Description}" />
</DataTemplate>

, , ItemsSource ObservableCollection ( ).

0

All Articles