【问题标题】:WPF combo box headerWPF 组合框标题
【发布时间】:2018-04-02 14:33:27
【问题描述】:

如果单击组合框图标并且需要显示文本,我只需要在组合框中显示图标。因为我不熟悉如何实现这一点。

请帮助我实现这一目标。

<ComboBox Name="cmbColors">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

这将显示组合框中的矩形和文本以及组合框的下拉菜单。但我的要求只是在组合框中显示填充颜色的矩形。

【问题讨论】:

  • 听起来您需要将命令附加到组合框(selectionchanged 事件可能是合适的)并创建与文本块的可见性属性的绑定,该属性在选择时会发生变化。
  • @Sudsy1002 一个小例子会很有帮助
  • 你的意思是你想要一个不同的模板用于所选项目,当组合不下拉到下拉时弹出窗口中显示的项目的模板时显示该模板? stackoverflow.com/questions/21776117/…

标签: c# .net wpf combobox controltemplate


【解决方案1】:

我不确定我是否理解你想要做什么,但我最好的猜测是,如果其他控件有焦点,你想隐藏文本块。如果是这样,你可以这样做:

<ComboBox>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" />
                <TextBlock x:Name="text" Text="{Binding Name}" />
            </StackPanel>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding IsKeyboardFocusWithin, RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}}" Value="False">
                    <Setter TargetName="text" Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

如果您试图说您想要一个与下拉列表不同的标题模板,那么您可以执行this question 的答案之一中所述的操作。

<ComboBox>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" />
                <TextBlock x:Name="text" Text="{Binding Name}" />
            </StackPanel>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBoxItem}}}" Value="{x:Null}">
                    <Setter TargetName="text" Property="Visibility" Value="Collapsed" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

【讨论】:

  • 我的要求是第二个,我会在我的示例中尝试这个,让你知道它是否适合我。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
相关资源
最近更新 更多