Hi,
I am using a ComboBox control in a WPF UserControl. I have binded it to a Entity. The problem is if I type text manually (IsEditable = "True")
the Text sometimes does not match with the DisplayMemberPath Value of the SelectedValue.
This is my Xaml Code:
ItemsSource="{Binding Companies, Mode=OneWay}"
DisplayMemberPath="Name"
SelectedValue = "{Binding SelectedItem.CompanyId, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"
SelectedValuePath="CompanyId"
IsSynchronizedWithCurrentItem="True"
IsEditable="True"
And this C# Companies (ItemSource):
public class CompanyEntity : BaseEntity
{
public int? CompanyId { get; set; }
public string Name
{
get
{
return GetValue(() => Name);
}
set
{
SetValue(() => Name,value);
}
}
}
(where GetValue and SetValue reproduces OnNotifiPropertyChanged.)
So, if I have this companies:
CompanyId:1 Name: Microsoft
CompnayId:2 Name: Apple
If I type manually "Mi", the ComboBox automatically select "Microsoft (SelectedValue = 1, Text = Microsoft). But If I delete the last word, SelectedValue remains 1 and Text changes to "Mi". So I have selected a value that does not correspond to Company with Id=1.
¿Anyone has experimented this issue and knows hoy to resolve it?
What I have tried:
I tried to change SelectedValue manually on this way:
ComboBox Xaml Code:
TextBoxBase.TextChanged="ComboBox_TextChanged"
C# view code behind:
private void ComboBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (sender is ComboBox)
{
ComboBox combo = sender as ComboBox;
if (!String.IsNullOrWhiteSpace(combo.Text))
{
if (combo.SelectedValue == null || (int)combo.SelectedValue == 0)
return;
else
{
var propertyInfo = combo.SelectedItem.GetType().GetProperty(combo.DisplayMemberPath);
string value = propertyInfo.GetValue(combo.SelectedItem, null).ToString();
if (!value.Equals(combo.Text, StringComparison.OrdinalIgnoreCase))
{
combo.SelectedValue = 0;
}
}
}
}
}
But in this case, when I update SelectedValue it automatically deletes Text.
Other option I have tried is updating Text after SelectedValue = 0, but then the cursor moves to the begining, whit a poor user experience.