我将数据库表的主键绑定到组合框的selectedIndex。问题发生在主键从1开始但selectedIndex从0接受的时候。我的意思是,当我想在数据库中看到ID = 1的项目时,因为它被列为组合框中的第一个元素,索引为0,它显示第二个元素在列表中,组合框中ID = 1。任何人都可以帮我解决这个问题吗?
提前致谢。 这是我的组合框:
<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 :(得分:4)
如何使用ComboBox的SelectedValuePath
和DisplayMemberPath
,并使用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}" />
答案 1 :(得分:0)
将属性IsSynchronizedWithCurrentItem
(在您的XAML中)设置为True
有帮助吗?
修改强> 也许这个链接会有所帮助:
http://social.msdn.microsoft.com/Forums/en/wpf/thread/b4e84ea2-9597-4af1-8d3c-835b972e3d73
答案 2 :(得分: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中插入断点来调试它。