简体   繁体   English

WPF ComboBox:对齐选定的值和/或下拉项

[英]WPF ComboBox: Align selected value and/or drop down items

I have an almost default WPF ComboBox:我有一个几乎默认的 WPF ComboBox:

在此处输入图片说明

What is the simplest way to align items, for instance, to the right in combobox's input and/or drop down?例如,在组合框的输入和/或下拉菜单中对齐项目的最简单方法是什么

I've looked around and found only solutions messing with the control templates which in my opinion is too long shot for such a simple thing.我环顾四周,发现只有与控制模板混淆的解决方案,在我看来,这对于这么简单的事情来说太远了。 I can't believe there is no simpler solution we can do for aligning the items.我不敢相信没有更简单的解决方案可以用来对齐项目。

UPDATE : I've slightly reformulated the question to cover a broader set of cases further readers might experience on this topic as it turned out thanks to dkozl's answer.更新:我稍微重新表述了这个问题,以涵盖更多读者可能会在这个主题上遇到的更广泛的案例,因为多亏了 dkozl 的回答。

Also, it should prevent some people from trying to close this question as a duplicate.此外,它应该防止某些人试图将这个问题作为重复来关闭。

If you want to right align both selected value and drop down items then setting HorizontalContentAlignment="Right" against ComboBox should be enough 如果要同时右对齐选定的值和下拉菜单项,那么对ComboBox设置HorizontalContentAlignment="Right"就足够了

<ComboBox ... HorizontalContentAlignment="Right">

if you want to right align only drop down items then you need to change HorizontalContentAlignment of the ComboBoxItem 如果只想使下拉项右对齐则需要更改ComboBoxItem HorizontalContentAlignment

<ComboBox>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="HorizontalContentAlignment" Value="Right"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

and to right align only selected value combination of both 并右对齐将两者的选定值组合

<ComboBox ... HorizontalContentAlignment="Right">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

我已经尝试了dkozl的答案,并且出于某种原因,对我的ComboBox设置HorizontalContentAlignment足以使combobox的输入和下拉菜单中的正确项对齐。

I had the problem of aligning the selected item on the right, so that users can always see the end of the string.我遇到了在右侧对齐所选项目的问题,以便用户始终可以看到字符串的结尾。 Simplest solution I found was the following我发现的最简单的解决方案如下

<ComboBox ...>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock HorizontalAlignment="Right" Text="{Binding textProp}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

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

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