.net wpf - 具有綁定到值的可編輯ComboBox不在列表中





tutorial c# (3)


將綁定設置為Combo的Text屬性也足夠了。

<ComboBox  IsTextSearchEnabled="True"    IsEditable="True" 
ItemsSource="{Binding Items}" Text="{Binding SelectedItemText, Mode=TwoWay}" />

我有可編輯的組合框,其中並不總是首選項位於下拉列表中。

我希望有可能在文本框中手動輸入文本,該文本傳播到綁定到SelectedValue的字符串。

現在,只有在ComboBox項目中輸入的值為on時,才會更新綁定到SelectedValue的字符串。

如何允許手動輸入ComboBox列表中不可用的自定義值並將其正確傳播到綁定值?




我昨天和今天剛剛這樣做,它看起來如下:

  1. 設置組合框IsEditable="true"

  2. 而不是綁定到SelectedItem ,綁定到組合框的Text屬性

  3. 如果您綁定到自定義對象而不僅僅是字符串,則還需要設置TextSearch.TextPath="NameOfField" 。 這使文本搜索行為起作用,並且還在文本框中顯示此屬性。

總而言之,我最終得到了類似的東西:

<ComboBox x:Name="c" 
          IsEditable="True" 
          IsTextSearchEnabled="True" 
          IsTextSearchCaseSensitive="False" 
          StaysOpenOnEdit="True"
          Text="{Binding NameOnViewModel}"
          TextSearch.TextPath="NameOnChildItems"  
          ItemsSource="{Binding Items}" 
          ItemTemplate="{StaticResource DataTemplate}" />

<TextBlock Text="{Binding ElementName=c,Path=Text}" />



It depends on the behaviour of your "team" object. If it behaves just like a collection, it might be OK to represent it first with a plain List. Then you might start to notice that you keep duplicating code that iterates on the list; at this point you have the option of creating a FootballTeam object that wraps the list of players. The FootballTeam class becomes the home for all the code that iterates on the list of players.

It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?

Encapsulation. Your clients need not know what goes on inside of FootballTeam. For all your clients know, it might be implemented by looking the list of players up in a database. They don't need to know, and this improves your design.

It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.

Exactly :) you will say footballTeam.Add(john), not footballTeam.List.Add(john). The internal list will not be visible.





.net wpf combobox editing