2010-08-26 75 views
0

我將數據庫表的主鍵綁定到組合框的selectedIndex。問題發生在主鍵從1開始,但selectedIndex從0開始接受。我的意思是,當我想在數據庫中看到ID = 1的項目時,因爲它被列爲索引爲0的組合框中的第一個元素,它顯示第二個元素在組合框中被認爲ID = 1的列表中。任何人都可以幫助我解決這個問題嗎?Combobox中的數據綁定

在此先感謝。 這裏是我的組合框:

<ComboBox SelectedIndex="{Binding SC.User1.UserID, UpdateSourceTrigger=PropertyChanged }"   
      IsSynchronizedWithCurrentItem="True" 
      x:Name="proxyResponsibleUserCmb" ItemsSource="{Binding Users, Mode=OneTime}" 
      SelectedItem="{Binding SC.User1.FullName, ValidatesOnDataErrors=True,     
         UpdateSourceTrigger=PropertyChanged}" 
      Validation.ErrorTemplate="{x:Null}" 
      Height="23" 
      VerticalAlignment="Top" 
      HorizontalAlignment="Left" 
      Width="118" 
      Margin="184,3,0,0" 
      Grid.Row="0" 
      Grid.Column="1"/> 
+0

你能提供一些代碼嗎?例如。如果您的selectedIndex是一個屬性,爲什麼不在那裏進行計算? – 2010-08-26 07:18:37

回答

4

如何使用組合框的SelectedValuePathDisplayMemberPath,並使用SelectedValue而不是SelectedItem設置默認項目?

<ComboBox x:Name="proxyResponsibleUserCmb" 
    SelectedValuePath="{Binding UserID}" 
    DisplayMemberPath="{Binding FullName}" 
    SelectedValue="{Binding SC.User1.UserId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" 
    ItemsSource="{Binding Users, Mode=OneTime}" /> 
0

快速的解決方法通過ValueConverter:

在你的代碼隱藏創建ValueConverter:

// of course use your own namespace... 
namespace MyNameSpace 
{ 
public class IndexConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if(!(value is int)) // Add the breakpoint here!! 
      throw new Exception(); 
     int newindex = ((int)value - 1; 
     return newindex; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException("This method should never be called"); 
    } 
} 
} 

然後,使它在您的XAML中已知:

//(declare a namespace in your window tag:) 
xmlns:myNamespace="clr-namespace:MyNameSpace" 

// add: 
<Window.Resources> 
    <ResourceDictionary> 
     <myNamespace:IndexConverter x:Key="indexConverter" /> 
    </ResourceDictionary> 
</Window.Resources> 

然後改變你的綁定:

<ComboBox SelectedIndex="{Binding SC.User1.UserID, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource indexConverter}}" ... /> 

這應該做的伎倆。至少你可以通過在IndexConverter中插入一個斷點來調試它。

+0

謝謝你的解決方案,但我意識到,當從數據庫中刪除用戶時,該技巧將失敗,因此訂單不再與ComboBox的索引同步。 所以我仍然需要另一個解決方案來做出正確的選擇。 – cemregoksu 2010-08-26 09:59:23

+0

現在我可以更新選定的項目 - 我可以通過調試來看到它 - 但我無法在選定的組合框中看到它。組合框中沒有顯示任何內容。你有什麼想法,爲什麼發生以及如何解決? – cemregoksu 2010-08-27 08:49:38

+0

如果您希望組合框在不重新加載頁面的情況下更新數據更改,則應考慮將ViewModel放置在它們之間並綁定到其ObservableCollection,或者至少綁定到可引發OnPropertyChanged事件的某些屬性。我的解決方案對於靜態數據庫數據是快速的。 – 2010-08-27 09:01:56