You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MaterialDesign中如何通过ToggleButton控制ComboBox显隐且无需后台代码

你可以直接通过XAML原生的绑定+触发器能力实现,完全不需要编写任何后台逻辑代码,以下是两种可行方案:

方案1:使用BooleanToVisibilityConverter(最简洁)

首先在页面/窗口的资源字典中声明转换器:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>

然后修改你的布局代码,添加ComboBox,将其Visibility属性直接绑定到ToggleButton的IsChecked属性即可:

<Grid Grid.Row="0" VerticalAlignment="Center">
    <TextBlock  Text="Máy in hóa đơn :"
       Foreground="White" Margin="15,20,0,0"/>
    <!-- 给ToggleButton加个名称方便绑定 -->
    <ToggleButton x:Name="InvoicePrintToggle" 
                  VerticalAlignment="Top" 
                  HorizontalAlignment="Right" 
                  Margin="0,20,120,0"/>
    <!-- 新增的ComboBox,绑定ToggleButton的选中状态 -->
    <ComboBox x:Name="PrintConfigCombo"
              VerticalAlignment="Top"
              HorizontalAlignment="Right"
              Margin="0,20,10,0"
              Visibility="{Binding IsChecked, ElementName=InvoicePrintToggle, Converter={StaticResource BoolToVis}}">
        <!-- 此处填写你的ComboBox选项内容 -->
    </ComboBox>
</Grid>

方案2:使用Style触发器(无需额外声明转换器)

如果不想额外添加转换器,可以直接给ComboBox写内置的触发器实现效果:

<Grid Grid.Row="0" VerticalAlignment="Center">
    <TextBlock  Text="Máy in hóa đơn :"
       Foreground="White" Margin="15,20,0,0"/>
    <ToggleButton x:Name="InvoicePrintToggle" 
                  VerticalAlignment="Top" 
                  HorizontalAlignment="Right" 
                  Margin="0,20,120,0"/>
    <ComboBox x:Name="PrintConfigCombo"
              VerticalAlignment="Top"
              HorizontalAlignment="Right"
              Margin="0,20,10,0">
        <ComboBox.Style>
            <Style TargetType="ComboBox">
                <!-- 默认未选中时隐藏 -->
                <Setter Property="Visibility" Value="Collapsed"/>
                <Style.Triggers>
                    <!-- ToggleButton选中时显示 -->
                    <DataTrigger Binding="{Binding IsChecked, ElementName=InvoicePrintToggle}" Value="True">
                        <Setter Property="Visibility" Value="Visible"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ComboBox.Style>
        <!-- 此处填写你的ComboBox选项内容 -->
    </ComboBox>
</Grid>

两种方案都适配你使用的MaterialDesign控件库,不会和现有样式冲突,实现的效果和你预期一致:

  • 未选中(关闭)状态:
    未选中(关闭)状态的ToggleButton开关
  • 选中(开启)状态:
    选中(开启)状态的ToggleButton开关,旁侧显示ComboBox

内容的提问来源于stack exchange,提问作者Harry Phan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:45:03