我有this同样的问题,但提出的解决方案不起作用,我找不到任何其他解决方案。我想创建一个ComboBox
CheckBox
作为ItemTemplate
的一部分。这已经完成了。但是当用户点击CheckBox
时会出现问题:PopUp
关闭。我需要它保持开放。
我尝试处理ComboBox.SelectionChanged
事件和CheckBox.Click
事件,但我无法理解。从跟踪代码开始,当用户单击CheckBox
时,似乎根本不会触发SelectionChanged事件,这与TextBox
部分中没有任何内容的控件的行为相匹配。 / p>
这不是用于多重选择,而是将CheckBox
绑定到数据上下文中的属性。
以下是一些示例代码
<Toolbar VerticalAlignment="Top">
<ComboBox x:Name="comboBox" SelectionChanged="ComboBox_SelectionChanged">
<ComboBox.ItemTemplate>
<DataTemplate DataType="local:MyType">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<CheckBox Click="CheckBox_Clicked"/>
<TextBlock Text="{Binding Title}" Grid.Column="1"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
<local:MyType Title="item 1"/>
<local:MyType Title="item 2"/>
<local:MyType Title="item 3"/>
<local:MyType Title="item 4"/>
</ComboBox>
</Toolbar>
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// do some stuff
}
private void CheckBox_Clicked(object sender, RoutedEventArgs e)
{
// change a property on the data context if not data bound
// Tried this, but Popup just closes then reopens
comboBox.IsDropDownOpen = true;
// This seems to have no effect
e.Handled = true;
}
有人可以帮忙吗?
修改
我注意到ComboBox
放置在Toolbar
时存在行为差异。如果不在Toolbar
中,则其行为符合预期:CheckBox
更改状态而不关闭Popup
。但是在ToolBar
中,无论点击位于何处,Popup
都会在第一次点击时关闭。请试试新代码。我真的需要在工具栏中使用它。
编辑2:
对于后代和任何搜索它的人,MS suggested将DataTemplate中CheckBox的Focusable属性设置为false。这达到了预期的效果。
答案 0 :(得分:1)
似乎Toolbar
控件以某种方式影响ComboBox
控件。奇怪的是,当您将光标置于ComboBox
内时TextBox
未关闭,但CheckBox
的工作错误。
解决此问题的最快方法是在用户点击CheckBox
时手动更改焦点。
我使用以下一系列步骤:
1)处理应用程序中每个控件的GotFocus
事件
2)仅保留CheckBox
控件的事件
3)检查CheckBox
是否在当前ComboBox
4)如果是,请将焦点返回ComboBox
public MainWindow()
{
InitializeComponent();
//...
comboBox.AddHandler(FrameworkElement.GotFocusEvent, (RoutedEventHandler)OnGotFocus);
}
private void OnGotFocus(object sender, RoutedEventArgs e)
{
if (e.OriginalSource is CheckBox)
{
var comboBox = (ComboBox)sender;
var comboBoxItem = GetParentElement<ComboBoxItem>(e.OriginalSource);
if (comboBoxItem != null && comboBox.Items.OfType<object>().Select(comboBox.ItemContainerGenerator.ContainerFromItem).Contains(comboBoxItem))
comboBox.Focus();
}
}
private T GetParentElement<T>(object element) where T : DependencyObject
{
var current = element as DependencyObject;
while (current != null && !(current is T))
{
current = VisualTreeHelper.GetParent(current);
}
return current as T;
}
这是一个非常混乱的解决方案,但无论如何它都有效。
答案 1 :(得分:0)
您需要的是Check ComboBox控件,它是WPF扩展工具包的一部分。您可以在此处找到它:Check ComboBox