繁体   English   中英

WPF组合框就像弹出窗口一样

[英]WPF combobox like popup

我正在尝试制作一个类似于组合框的自定义弹出窗口。

我使用了一个Toggle按钮作为标题,并使用Popup作为内容。

<ToggleButton IsChecked="{Binding ElementName=Popup, Path=IsOpen, Mode=TwoWay}">
...
</ToggleButton>

<Popup x:Name="Popup" StaysOpen="False">
...
</Popup>

除了一个案例,这个工作很好。 当弹出窗口打开并再次单击ToggleButton时,弹出窗口消失,但随后重新打开。

看起来当我点击切换按钮时,Popup检测到鼠标单击位于弹出窗口之外,因此它自行关闭并设置ToggleButton.IsChecked = false 然后单击设置IsChecked = true ,弹出窗口再次打开。

编辑:在这种情况下,我希望弹出窗口关闭就像Combobox的行为一样。

有没有办法解决这个问题?

两种方式。

一种是在按钮顶部找到弹出窗口,这样用户就无法点击按钮。 我不喜欢那个,但你可以通过Placement等轻松完成。

另一种是使用布尔型“非”转换器将ToggleButton.IsEnabled绑定到Popup.IsOpen ,因此只要弹出窗口打开,该按钮就会被禁用。

您也可以使用按钮上的样式DataTrigger执行此操作,如下所示:

<ToggleButton 
    x:Name="PopupButton"
    Content="Open Popup"
    IsChecked="{Binding ElementName=Popup, Path=IsOpen}">
    <ToggleButton.Style>
        <Style TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsOpen, ElementName=Popup}" Value="True">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

<Popup 
    x:Name="Popup" 
    StaysOpen="False"
    PlacementTarget="{Binding ElementName=PopupButton}" 
    Placement="Bottom"
    >
    <Label 
        Padding="20" 
        Background="WhiteSmoke" 
        BorderBrush="Black" 
        BorderThickness="1">Content</Label>
</Popup>

请注意,在IsChecked绑定上不需要Mode=TwoWay 这是该属性的默认值。

如果你有多个这样的话,我会用一个ControlTemplate编写一个Style for HeaderedContentControl ,它将标题放在ToggleButton内容中, Popup的内容,并使用ControlTemplate触发器启用ToggleButton

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM