2010-08-26 94 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