How do stop Lost_focus on click of ComboBox in WPF?
Mojtaba_Hakim
281
Reputation points
I use C# WPF
What I need :
When focus lost on ComboBox , check if ComboBox has no a valid item Show a Error .
My Problem :
In this case when I click on the ComboBox the LostFocus event will fire
but it seems didn't happened , in google search I found this :
What I did :
MyXAML :
<ComboBox x:Name="SecoundCombo" HorizontalAlignment="Left" Margin="95,105,0,0" VerticalAlignment="Top" Width="359" LostFocus="SecoundCombo_LostFocus" IsEditable="True">
<ComboBoxItem Content="Jack" HorizontalAlignment="Left" Height="18" VerticalAlignment="Top" Width="402"/>
<ComboBoxItem Content="Sam" HorizontalAlignment="Left" Height="18" VerticalAlignment="Top" Width="402"/>
<ComboBoxItem Content="John" HorizontalAlignment="Left" Height="18" VerticalAlignment="Top" Width="402"/>
</ComboBox>
My Code Behind :
namespace TEST
{
public partial class MainWindow : Window
{
public static bool ComboisChoosedItem_Valid(ComboBox CMB)
{
bool st = true;
if (!string.IsNullOrEmpty(CMB.Text.Trim()) && CMB.SelectedIndex > -1 && CMB.SelectedItem != null)
{
if (CMB.Items.OfType<ComboBoxItem>().Any(cbi => cbi.Content.Equals(CMB.Text)))
{
//ComboBox is Not Empty is Correct Item Selected
st = true;
}
}
else
{
//ComboBox Is Empty Or Not Correct Item Selected
st = false;
}
return st;
}
public MainWindow()
{
InitializeComponent();
}
private void SecoundCombo_LostFocus(object sender, RoutedEventArgs e)
{
if (e.OriginalSource != sender) return;
if (ComboisChoosedItem_Valid(SecoundCombo) == false)
{
MessageBox.Show("Please choose valid item from list");
SecoundCombo.IsDropDownOpen = true;
}
}
}
}
What have I tried for LostFocus Problem :
var textBox = SecoundCombo.Template.FindName("PART_EditableTextBox", SecoundCombo) as TextBox;
if (textBox.IsFocused != true)
{
if (ComboisChoosedItem_Valid(SecoundCombo) == false)
{
MessageBox.Show("Please Choose an item");
SecoundCombo.IsDropDownOpen = true;
}
}
summry : Why Lost Focus Happened when did not happen because I was focused on something else and I clicked on the CombBox for First time