组合框打开时Silverlight Combobox Fire KeyDown事件

时间:2017-10-02 20:44:10

标签: c# .net xaml silverlight combobox

我有一个Silverlight Combobox(碰巧在StackPanel中),KeyDown事件上有一个事件处理程序。处理程序仅在ComboBox关闭时才有效,因此只需点击2次就可以触发它。

有没有办法在ComboBox打开时触发KeyDown事件或执行等效操作?

1 个答案:

答案 0 :(得分:1)

您必须在KeyUp/KeyDown模板中处理ItemsPresenter的{​​{1}}。在我的测试中,与ComboBox相比,KeyUp提供了更平滑的过渡。

enter image description here

编辑:如果您必须将自己的风格保存在单独的字典中,那么您可以这样做:

<强> XAML:

KeyDown

<强> MyComboBox:

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication5"
    x:Class="SilverlightApplication5.MainPage"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <StackPanel Orientation="Horizontal"
                    VerticalAlignment="Center"
                    HorizontalAlignment="Center">
            <local:MyComboBox x:Name="cbx1" 
                      FontSize="24"
                      SelectedIndex="0"
                      Margin="0,0,10,0"
                      Style="{StaticResource ComboBoxStyle1}">
                <ComboBoxItem Content="Option 1"/>
                <ComboBoxItem Content="Option 2"/>
                <ComboBoxItem Content="Option 3"/>
            </local:MyComboBox>
            <TextBlock x:Name="txt1" 
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   FontSize="24"
                   Text="{Binding ElementName=cbx1, Path=SelectedItem.Content}"/>
        </StackPanel>
    </Grid>
</UserControl>

<强>词典:

public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        this.DefaultStyleKey = typeof(MyComboBox);
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        var itemsPresenter = GetTemplateChild("Ip1") as UIElement;

        if (itemsPresenter != null)
            itemsPresenter.KeyUp += ItemsPresenter_KeyUp;

    }

    private void ItemsPresenter_KeyUp(object sender, KeyEventArgs e)
    {
        SelectedItem = e.OriginalSource;
    }
}