我发布了一个类似的问题here并且无法成功实施向我建议的解决方案,因为它无法正常工作。我找到了一种方法,并希望通过绑定来改进它组合框到自定义对象以启用数据验证。这个是xaml
<Window xmlns:data="clr-namespace:Myproject">
<Window.Resources>
<data:UserLogin x:Key="user"></data:UserLogin>
<DataTemplate x:Key="comboTemplate">
<TextBlock Text="{Binding Path=username}" />
</DataTemplate>
</Window.Resources>
<ComboBox Margin="18,121,24,0" Name="cmbEmail" Tag="email" TabIndex="1" ToolTip="enter the email you signed up with here" IsEditable="True" IsSynchronizedWithCurrentItem="True" ItemTemplate="{StaticResource comboTemplate}" ItemsSource="{Binding}" Height="23" VerticalAlignment="Top" Style="{DynamicResource cmbBoxerrors}">
<ComboBox.Text>
<Binding Path="Loginname" Source="{StaticResource user}" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
</Window>
和xaml.cs是
if (con != null)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCeCommand cmdusers = new SqlCeCommand("select * from users order by id", con);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmdusers);
userdt = new DataTable("users");
da.Fill(userdt);
cmbEmail.DataContext = userdt;
}
和UserLogin类是
class UserLogin :IDataErrorInfo
{
private string _loginname = "";
private string _password;
public string this[string columnName]
{
get
{
string result = null;
if(columnName == "Loginname")
{
if(string.IsNullOrEmpty(this._loginname))
{
result = "Login Name cannot be Empty";
}
}
if (columnName == "Loginname")
{
if(!Util.ValidateRegexPatern(Properties.Resources.emailRegex,this._loginname))
{
result = "MalFormed Email address. Please write a correct email addess";
}
}
return result;
}
}
public string Error
{
get { return null; }
}
public string Password
{
get { return _password; }
set { _password = value; }
}
public string Loginname
{
get { return _loginname; }
set { _loginname = value; }
}
}
问题是当我使用ItemTemplate
所选项目显示System.Data.DataRowView
但下拉列表项正确显示时以及当我将ItemTemplate
与DisplayMemberPath
交换时,其行为与在所选项目中是正确的,下拉列表项目显示System.Data.DataRowView
。使用它们都会抛出异常,因为我无法使用它们同时选中和下拉列表项正确显示。
我真的不知道我做得不好。任何人都可以对此有所了解我会非常感谢。谢谢你的阅读
答案 0 :(得分:1)
它是这样的:您将ComboBox的数据上下文设置为DataTable类型的实例。然后将ItemsSource设置为{Binding},这意味着ComboBox中的每个项都将绑定到DataRow(它既没有loginname,也没有username作为属性)。在这里绑定停止工作。没有隐含的方法可以从DataRow转换为UserLogin。
您可以实现转换器进行转换或将行逐个转换为UserLogin,并将ComboBox的DataContext设置为UserLogin列表(如果需要更高级的功能,则设置为ObservableCollection)。
在任何一种情况下,请删除<ComboBox.Text> ... </ComboBox.Text>
部分。
希望这可以帮助你...