我有一个Silverlight Combobox(碰巧在StackPanel中),KeyDown事件上有一个事件处理程序。处理程序仅在ComboBox关闭时才有效,因此只需点击2次就可以触发它。
有没有办法在ComboBox打开时触发KeyDown事件或执行等效操作?
答案 0 :(得分:1)
您必须在KeyUp/KeyDown
模板中处理ItemsPresenter
的{{1}}。在我的测试中,与ComboBox
相比,KeyUp
提供了更平滑的过渡。
编辑:如果您必须将自己的风格保存在单独的字典中,那么您可以这样做:
<强> 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;
}
}