2014-10-27 459 views
2

我在我的WPF應用程序中顯示項目列表的組合框。大多數情況下,第一個項目是項目源列表中的正確選擇,有時僅在個人請求時才能更改項目。現在我的組合框加載列表,但從不顯示選定項目的第一個項目。請有人能幫助我嗎?這是我的代碼。wpf combobox默認從itemssource中選擇

XAML:

<ComboBox Name="cbxShipTo" TabIndex="0" IsTextSearchEnabled="True" ToolTip="Ship To is a Required Field" MinWidth="200" SelectedIndex="0" IsSynchronizedWithCurrentItem="True" 
IsEditable="False" DisplayMemberPath="ShipToCountyState" SelectedValuePath="ShipToValue"> 
<ComboBox.SelectedValue> 
    <Binding Path="ShipToQAD" Mode="TwoWay"> 
     <Binding.ValidationRules> 
      <common:RequiredValidationRule ErrorMessage="Ship To is a Required Field" /> 
      <ExceptionValidationRule></ExceptionValidationRule> 
     </Binding.ValidationRules> 
    </Binding> 
</ComboBox.SelectedValue> 

代碼背後:

cbxShipTo.ItemsSource = dbLookupService.GetShipToByCustomer(_inspectionListItems[0].CompanyID); 
cbxShipTo.SelectedItem = cbxShipTo.Items.GetItemAt(0); 

我在的ItemsSource值,選擇紡織機械展覽會哈薩值太多,但永遠不會被顯示在屏幕上。

任何幫助表示讚賞。

+1

不重複,但相關:http://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath我個人會仔細混合'SelectedValue'和'SelectedItem' – BradleyDotNET 2014-10-27 20:11:20

+1

爲什麼你在另一個地方設置'SelectedIndex',但在另一個地方設置'SelectedItem'?此外,您正在Xaml中設置與「SelectedValue」相關的值,但您在後面的代碼中設置了「SelectedItem」。選擇一種選擇機制並堅持下去。當你將三者混合時,遇到問題並不奇怪。 – 2014-10-27 20:13:11

+0

我嘗試了兩種不同的東西,但沒有在我的情況下工作。即使我沒有SelectedItem,組合框也不會顯示該值。 – 2014-10-27 20:16:22

回答

2

我通常這樣做的方式是保持對ViewModel中當前選定項目的引用。 (無論如何,您應該可以這樣做,因爲您不應該查詢UI對象本身來找出用戶的選擇。)將YourSelectedItem初始化爲您希望顯示爲選定項的項目。

public List<YourType> YourItems { get; set; } 
public YourType SelectedItem = YourItems[index]; 

然後將SelectedItem綁定到YourItems屬性。

<ComboBox ... SelectedItem={Binding YourSelectedItem, Mode=TwoWay} ... /> 

只要用戶在組合框中更改了他們的選擇,YourSelectedItem屬性就會自動更新。

您不應該使用SelectedItem以外的其他任何內容。

+0

偉大的工作....感謝您的快速響應。擺脫SelectedValue並使用SelectedItem代替,現在它顯示出來。 – 2014-10-27 20:22:35

+0

太棒了!感謝您接受答案。 – furkle 2014-10-27 20:23:18