How to add a focus style to an editable ComboBox in WPF

自古美人都是妖i 提交于 2019-12-13 16:23:37

问题


I've been looking at the following example on how to style the ComboBox, but I haven't been able to create a focus effect when going into an editable combo box. Whenever the ComboBox receives focus, it should go into edit mode and the component should have a focus style.

The basic problem is that whenever I go into the edit mode, it's not the surrounding ComboBox which actually has the focus, but the text subcomponent and I haven't been able to create a Trigger on the text component which modifies the ComboBox's border style since I don't know how to refer to the parent component from the trigger.

I've tried adding ControlTemplate Trigger on the TextBox, or style trigger. I've tried to refer to the ComboBox by name or by using the TemplateBinding option, but without any luck. A simple example would be very appreciated.


回答1:


Bind IsKeyboardFocusWithin to IsDropDownOpen

<ComboBox ItemsSource="{Binding SortedItems}"
          StaysOpenOnEdit="True"
          IsDropDownOpen="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource Self}, Mode=OneWay}" />



回答2:


  private void cmbSpecialHandling_GotFocus(object sender, RoutedEventArgs e)
        {
            Thickness th = new Thickness(2);
            cmbSpecialHandling.BorderThickness = th;
            cmbSpecialHandling.BorderBrush = this.FindResource("TabFocusColor") as SolidColorBrush;
        }

        private void cmbSpecialHandling_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            Thickness th = new Thickness(2);
            cmbSpecialHandling.BorderThickness = th;
            cmbSpecialHandling.BorderBrush = this.FindResource("TabFocusColor") as SolidColorBrush;
        }

        private void cmbSpecialHandling_LostFocus(object sender, RoutedEventArgs e)
        {
            cmbSpecialHandling.BorderBrush = Brushes.Transparent;
        }



回答3:


Set the border brush of combobox in its Gotfocus and make it transparent in lost focus:

private void comboBox_GotFocus(object sender, RoutedEventArgs e)
    {
        Thickness th = new Thickness(2);
        comboBox.BorderThickness = th;
        comboBox.BorderBrush = this.FindResource("TabFocusColor") as SolidColorBrush;
                  or
     comboBox.BorderBrush = Brushes.Green;
    }


    private void comboBox_LostFocus(object sender, RoutedEventArgs e)
    {
        comboBox.BorderBrush = Brushes.Transparent;
    }


来源:https://stackoverflow.com/questions/1543804/how-to-add-a-focus-style-to-an-editable-combobox-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!