WPF - 如何在点击后隐藏下拉菜单

5

我在我的WPF窗口中有一个SplitButton,它是从Xceed的Extended WPF Toolkit借来的。下拉内容由一些RadioButton组成。类似这样:

<Window x:Class="WpfTest.Test3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:tk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
        Title="Test3" Height="300" Width="300">
    <Grid Height="25" Width="150">
        <tk:SplitButton Content="Default Command">
            <tk:SplitButton.DropDownContent>
                <StackPanel>
                    <RadioButton Content="Default Command" GroupName="variations" Margin="5" IsChecked="True"/>
                    <RadioButton Content="Alternate Command 1" GroupName="variations" Margin="5"/>
                    <RadioButton Content="Alternate Command 2" GroupName="variations" Margin="5"/>
                </StackPanel>
            </tk:SplitButton.DropDownContent>
        </tk:SplitButton>
    </Grid>
</Window>

生成的效果如下:

test

问题是,当我点击每个 RadioButton 时,下拉菜单并没有消失。我查了一些资料,发现应该为每个 RadioButton 处理 Click 事件。但是我不知道如何在该事件处理程序中隐藏下拉菜单。另外,似乎 MenuItem 有一个名为 StaysOpenOnClick 的属性,但其他控件却没有。

虽然以编程方式完成可以满足需求,但是否有MVVM方式实现呢?


1
不是针对您的问题的解决方案,但为什么您更喜欢单选按钮而不是下拉列表? - Dennis Schröer
@Zure 什么是下拉列表?SplitButton有一个DropDownContent属性,可以填充MenuItem或类似我尝试的内容。我不明白你的意思。 - polfosol ఠ_ఠ
抱歉,我的意思是一个ComboBox:https://www.dotnetperls.com/combobox-wpf。 - Dennis Schröer
1个回答

5

在您的单选按钮上添加Checked事件,并使用SplitoButton.IsOpen = false;。按照以下代码。

Xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:tk="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <tk:SplitButton Name="SplitButton" Content="Default Command">

            <tk:SplitButton.DropDownContent>

                <StackPanel>
                    <RadioButton Checked="rb_Checked" Content="Default Command" GroupName="variations" Margin="5" IsChecked="True"/>
                    <RadioButton Checked="rb_Checked" Content="Alternate Command 1" GroupName="variations" Margin="5"/>
                    <RadioButton Checked="rb_Checked" Content="Alternate Command 2" GroupName="variations" Margin="5"/>
                </StackPanel>

            </tk:SplitButton.DropDownContent>
        </tk:SplitButton>
    </Grid>
</Window>

.cs

 private void rb_Checked(object sender, RoutedEventArgs e)
        {
            SplitButton.IsOpen = false;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接