2009-04-12 58 views
5

我有一個綁定到WPF中的列表框的ObservableCollection。我希望ListBox是可編輯的,並且要將編輯更改保存到集合中。由於WPF不提供可編輯的列表框,我嘗試通過更改ListBox.ItemTemplate來創建自己的列表框。可編輯的WPF列表框

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

更改ItemTemplate中給了我編輯框,但文本框的任何變化不得到保存到的ObservableCollection。有沒有辦法讓一個具有雙向綁定的可編輯列表框?

回答

8

你不能這樣做。

要實現這種技巧,您需要將您的項目作爲「持有者類」,公開可以綁定文本框的屬性。

要理解它,想象一下以下調用僞序列:裝載被傳遞

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中與列表框)和項目(我假設你的情況的字符串) in。 在這一點上,它只知道字符串,並且不能向上影響任何東西。雙向綁定不能影響集合,因爲模板不知道它在哪個上下文中被使用,所以它無法回到原始集合並修改其內容。 對於這個問題,TextBox是一樣的。如果它沒有被賦予一個conainer和一個屬性名稱,它無處可以「存儲」這些變化。 這與將字符串傳遞給函數調用基本相同。該函數不能更改傳入的字符串(忽略像引用參數傳遞這樣的技巧)。

要回到你的情況,你需要建立其暴露包含需要編輯的值的屬性對象的集合:

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

然後你就可以在你的列表框綁定到這些集合項目和修改您的數據模板:

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

綁定到模型屬性 - 即數據對象的屬性 - 而不是視圖屬性,如Content。例如:

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

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

注意,如果您的ItemsSource是ObservableCollection(因爲沒有要綁定的屬性),這將不起作用。

+0

我不認爲我可以將文本框文本直接綁定到數據對象。在你的例子中,你綁定到單個字符串,但我的類有它們的集合,我不能將Text屬性設置爲字符串列表。 – 2009-04-13 03:11:06

+0

爲Items集合的每個成員重複DataTemplate,並將綁定設置爲該成員。 – itowlson 2009-04-13 03:51:04