2010-01-22 89 views
0
<CombobBox x:Name="cbo" 
      Style="{StaticResource ComboStyle1}" 
      DisplayMemberPath="NAME" 
      SelectedItem="{Binding Path=NAME}" 
      SelectedIndex="1"> 
    <ComboBox.ItemTemplate> 
    <DataTemplate> 
     <Grid> 
     <TextBlock Text="{Binding Path=NAME}"/> 
     </Grid> 
    </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

WindowOnLoaded事件,我寫的代碼來設置ItemsSource爲什麼這個WPF組合框不顯示選定的值?

cbo.ItemsSource = ser.GetCity().DefaultView; 

雖然裝載的窗戶,我可以看到最初的第一項加載,但在同一時間,它會清除顯示的項目。我被困在這種情況下,任何幫助表示讚賞。

問候

回答

4

快速回答:從代碼隱藏設置SelectedIndex = 1

看來,XAML中的代碼首先執行(InitializeComponent()方法),它設置了SelectedIndex = 1,但尚未指定ItemsSource!所以SelectedIndex不會影響! (請記住,你不能指定ItemsSourceInitializeComponent()

所以,你必須設置ItemsSource後手動設置SelectedIndex = 1


你應該這樣做:

XAML

  <ComboBox x:Name="cbo" 
         Style="{StaticResource ComboStyle1}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <Grid> 
          <TextBlock Text="{Binding Path=NAME}"/> 
         </Grid> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
      </ComboBox> 

代碼

 cbo.ItemsSource = ser.GetCity().DefaultView; 
    cbo.SelectedIndex = 1; 

或者這樣:

XAML

  <ComboBox x:Name="cbo" Initialized="cbo_Initialized" 
         Style="{StaticResource ComboStyle1}"> 
       <ComboBox.ItemTemplate> 
        <DataTemplate> 
         <Grid> 
          <TextBlock Text="{Binding Path=NAME}"/> 
         </Grid> 
        </DataTemplate> 
       </ComboBox.ItemTemplate> 
      </ComboBox> 

代碼

private void cbo_Initialized(object sender, EventArgs e) 
    { 
     cbo.SelectedIndex = 1; 
    } 

另外請注意,我已經刪除DisplayMemberPath="NAME"因爲你不能同時設置DisplayMemberPathItemTemplate在同一時間。而且,請使用SelectedItemSelectedIndex,而不是兩者。

+1

非常感謝您的意見。 – 2010-01-22 09:09:32

2

重置的ItemsSource將陷入困境的選擇。

此外,您正在設置SelectedItem和SelectedIndex。你只想設置其中的一個;如果您同時設置,則只有一個生效。

另外,您的SelectedItem聲明可能是錯誤的。 SelectedItem="{Binding NAME}"將查找與環境(可能是Window級別)DataContext的NAME屬性值相等的項目。這隻有在ComboBox.ItemsSource是一個字符串列表時纔有效。由於你的ItemTemplate工作,我假設ComboBox.ItemsSource實際上是一個城市對象的列表。但是你告訴WPF SelectedItem應該是一個字符串(一個名字)。該字符串永遠不會等於任何城市對象,因此結果將不會被選中。

因此,要解決這個問題,設置的ItemsSource,要麼設置或的SelectedItem的SelectedIndex,這取決於你的需求和你的數據模型後:

cbo.ItemsSource = ser.GetCity().DefaultView; 
cbo.SelectedIndex = 1; 
// or: cbo.SelectedItem = "Wellington"; // if GetCity() returns strings - probably not 
// or: cbo.SelectedItem = City.Wellington; // if GetCity() returns City objects 
+0

+1對於重置ItemsSource會弄亂選擇。我正在刷新我的ItemsSource,搞砸了綁定。 – 2012-12-26 17:00:50

相關問題