[英]WPF combobox databinding both to custom objects and to datatable.showing System.Data.DataRowView in dropdown list items
我在這里發布了一個類似的問題,由於無法正常工作,因此無法成功實施向我建議的解決方案。我找到了一種解決方法,並希望通過將組合框綁定到自定義對象來對其進行改進以啟用它數據驗證。這是此的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
。使用它們都引發異常,因為我不能同時使用它們,並且下拉列表項正確顯示。
我真的不知道我做錯了什么,誰能對此有所了解,我會非常感謝。感謝閱讀本文
它是這樣的:您將ComboBox的數據上下文設置為DataTable類型的實例。 然后,將ItemsSource設置為{Binding},這意味着ComboBox中的每個項目都將綁定到DataRow(該數據庫既沒有登錄名,也沒有用戶名作為屬性)。 綁定在這里停止工作。 沒有從DataRow轉換為UserLogin的隱式方法。
您既可以實現轉換器來進行轉換,也可以將行逐一轉換為UserLogin並將ComboBox的DataContext設置為UserLogin的列表(如果需要更高級的功能,也可以設置為ObservableCollection)。
無論哪種情況,都請放下<ComboBox.Text> ... </ComboBox.Text>
部分。
希望這對您有幫助...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.