在ComboBoxItem问题的单击事件后,WPF将ComboBox设置为-1索引

时间:2018-10-02 08:10:21

标签: c# .net wpf combobox

我有一个包含我的类别的组合框。在此组合框中,我还有一个名为<-​​NEW CATEGORY->的项目,该项目具有单击事件。现在,让我们忘记它会打开一个新窗口或一个对话框窗口以添加新类别的问题……现在,我想每当选择<-NEW CATEGORY->时,组合框选择的索引就会更改为-1。 / p>

<ComboBox x:Name="testcombo" HorizontalAlignment="Left" Margin="268,213,0,0" VerticalAlignment="Top" Width="120" Background="#FFC58383" DisplayMemberPath="data" SelectedValuePath="id">

                <ComboBox.ItemContainerStyle>
                    <Style TargetType="ComboBoxItem">
                        <EventSetter Event="PreviewMouseLeftButtonUp" Handler="ComboBoxItem_PreviewMouseLeftButtonUp"/>
                    </Style>
                </ComboBox.ItemContainerStyle>
</ComboBox>

和c#

namespace WpfApp4
{
    public partial class MainWindow : Window
    {
        public class Modell
        {
            public int id { get; set; }
            public string data { get; set; }
        }

        public MainWindow()
        {
            InitializeComponent();
            testcombo.Items.Add(new Modell { id = 0, data = "<--NEW-->" });
            testcombo.Items.Add(new Modell { id = 1 , data = "dddd" });
            testcombo.Items.Add(new Modell { id = 2, data = "dddzxcd" });
            testcombo.Items.Add(new Modell { id = 3, data = "ddczdd" });
        }



        private void ComboBoxItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var cat_obj = (sender as ComboBoxItem).Content as Modell;

            if (cat_obj.id == 0)
            {
                testcombo.SelectedIndex = -1;
                //MessageBox.Show("", "", MessageBoxButton.OK);
            }

        }
    }
}

问题是上面的代码没有将索引更改为-1,但是当我在行testcombo.SelectedIndex = -1;之后或之前添加消息框时,它起作用:|

注意:我无法在组合框SelectionChanged中将索引设为-1,因为在主项目中,我有keyUp事件,可通过键盘arrowUp / Down来选择项

1 个答案:

答案 0 :(得分:1)

使用Dispatcher使其有效:

private void ComboBoxItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    var cat_obj = (sender as ComboBoxItem).Content as Modell;

    if (cat_obj.id == 0)
    {
        Dispatcher.BeginInvoke((Action)(() => { testCombo.SelectedIndex = -1; }));
        //MessageBox.Show("", "", MessageBoxButton.OK);
    }

}

另一个解决方案可能是:

private void ComboBoxItem_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    var cat_obj = (sender as ComboBoxItem).Content as Modell;

    if (cat_obj.id == 0)
    {
        testCombo.SelectedIndex = -1;
        e.Handled = true;
        testCombo.IsDropDownOpen = false;
    }
}

问题是,在MouseLeftButtonUp发生后,combobx会进行项目选择,因此覆盖SelectedIndex = -1;。使用Dispatcher,您可以覆盖SelectedIndex,而这是通过单击鼠标设置的。使用第二种解决方案e.Handled = true;组合框根本不会选择项目,但是您需要手动关闭下拉菜单。