How do I prevent fire focus on click of ComboBox in WPF when the item is not in the list?

151 Views Asked by At

I use C# WPF

What I need :

When focus lost on ComboBox , check if ComboBox has no a valid item Show a Error .

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;
            }
        }      
    }
}

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 have I tried :

 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;
            }
        }

none of them work

Please help

1

There are 1 best solutions below

3
aca On

I'm not really sure what are you asking, but i think that this might help you - how to check if item is selected from a comboBox in C#