c# - 在 ComboBoxItem 模板中使用 DisplayMemberPath

标签 c# wpf xaml

目前,我已经对应该显示的 DataContext 对象的属性 (DisplayName) 进行了硬编码。但通常您在 ComboBox 本身中使用属性 DisplayMemberPath 指定此路径。如何使用 DisplayMemberPath 指定的值作为要在内容呈现器中绑定(bind)的属性?

<Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="SnapsToDevicePixels" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border x:Name="ItemBorder"
                            Padding="2,0"
                            BorderThickness="1"
                            CornerRadius="3">


                        <ContentPresenter Content="{Binding DisplayName}"/>


                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger SourceName="ItemBorder" Property="IsMouseOver" Value="True">
                            <Setter TargetName="ItemBorder" Property="Background" Value="{StaticResource LightBlueBackgroundBrush}"/>
                            <Setter TargetName="ItemBorder" Property="BorderBrush" Value="{StaticResource LightBlueBackgroundBrush}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

作为引用,这是我的 ComboBox 样式。

<Style TargetType="{x:Type ComboBox}">
    <Setter Property="SnapsToDevicePixels" Value="True" />
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
    <Setter Property="Height" Value="22"/>
    <Setter Property="Background" Value="White"/>
    <Setter Property="BorderBrush" Value="{StaticResource MidGreyBorderStroke}"/>
    <Setter Property="Border.CornerRadius" Value="3" />
    <Setter Property="IsEditable" Value="False" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">

                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="1"
                        CornerRadius="{TemplateBinding Border.CornerRadius}"
                        Width="{TemplateBinding Width}"
                        Height="{TemplateBinding Height}">

                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>

                        <ContentPresenter x:Name="ReadOnlyContentPresenter"
                                          Grid.Column="0"
                                          Margin="5,0"
                                          VerticalAlignment="Center"
                                          HorizontalAlignment="Left"
                                          Content="{TemplateBinding SelectionBoxItem}"
                                          ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                          ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" />

                        <TextBox x:Name="PART_EditableTextBox"
                                 Grid.Column="0"
                                 Margin="5,0"
                                 VerticalAlignment="Center"
                                 HorizontalAlignment="Center"
                                 Visibility="Hidden"
                                 IsReadOnly="{TemplateBinding IsReadOnly}" />

                        <Border Grid.Column="1"    
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="1,0,0,0"
                                Margin="0,2" />

                        <ToggleButton Grid.Column="2"
                                      Margin="1,0"
                                      Background="{TemplateBinding Background}"
                                      VerticalAlignment="Center"
                                      HorizontalAlignment="Right"
                                      Focusable="False"
                                      IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                      ClickMode="Press"
                                      Style="{StaticResource ComboBoxToggleButton}"/>

                        <Popup x:Name="PART_Popup"
                               AllowsTransparency="True"
                               Placement="Bottom"
                               IsOpen="{TemplateBinding IsDropDownOpen}"
                               Focusable="False"
                               PopupAnimation="Fade"
                               SnapsToDevicePixels="True">

                            <Grid Background="Transparent"
                                  MinWidth="{TemplateBinding ActualWidth}"
                                  MaxHeight="{TemplateBinding MaxDropDownHeight}">

                                <Border x:Name="DropDownBorder"
                                        Background="{TemplateBinding Background}"
                                        BorderBrush="{TemplateBinding BorderBrush}"
                                        BorderThickness="1"
                                        CornerRadius="{TemplateBinding Border.CornerRadius}"
                                        Margin="0,2,0,0">

                                    <ScrollViewer Margin="6,0">
                                        <StackPanel IsItemsHost="True"
                                                    KeyboardNavigation.DirectionalNavigation="Contained" />
                                    </ScrollViewer>
                                </Border>
                            </Grid>
                        </Popup>
                   </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Opacity" Value=".65" />
                    </Trigger>

                    <Trigger Property="HasItems" Value="false">
                        <Setter TargetName="DropDownBorder" Property="MinHeight" Value="42"/>
                    </Trigger>

                    <Trigger Property="IsEditable" Value="True">
                        <Setter Property="IsTabStop" Value="false"/>
                        <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible"/>
                        <Setter TargetName="ReadOnlyContentPresenter" Property="Visibility" Value="Hidden"/>
                    </Trigger>
                </ControlTemplate.Triggers>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

最佳答案

嗯,这实际上是一个有趣的问题,答案很简单。

简答:

   <ContentPresenter />

长答案:

如果您已经覆盖了 ComboBoxItem 样式,但您仍想使用 ComboBox 中的 DisplayMemberPath,则无需将任何内容放入样式 Content 绑定(bind)为 Parent(ComboBox) 将为您解决此问题。因为 DisplayMemberPath 只是一个字符串而不是实际属性,如果您绑定(bind)到 DisplayMemberPath,您的所有项目将只显示您放入 DisplayMemberPath 中的任何值/p>

因此,您所要做的就是从 ComboBoxItem 样式中删除 Content 绑定(bind)

例子:

<Style TargetType="{x:Type ComboBoxItem}">
    .............
    <Border x:Name="ItemBorder" Padding="2,0"  BorderThickness="1"  CornerRadius="3">
        <ContentPresenter /> <!-- no content binding -->
    </Border>

这是一个简单的例子,说明了这个工作

Xaml:

<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" x:Name="UI" Width="343" Height="744.625" >
    <Window.Resources>
        <Style TargetType="{x:Type ComboBoxItem}">
            <Setter Property="SnapsToDevicePixels" Value="True" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ComboBoxItem">
                        <Border x:Name="ItemBorder" Padding="2,0"  BorderThickness="1"  CornerRadius="3">
                            <ContentPresenter />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <StackPanel DataContext="{Binding ElementName=UI}">
        <ComboBox ItemsSource="{Binding Items}" DisplayMemberPath="Name" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120"/>
        <ComboBox ItemsSource="{Binding Items}" DisplayMemberPath="State" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120"/>
    </StackPanel>

</Window>

代码:

public partial class MainWindow : Window
{

    public MainWindow() 
    {
        InitializeComponent();

        for (int i = 0; i < 50; i++)
        {
            Items.Add(new ComboBoxModel { Name = "Name" + i, State = "State" + i });
        }
    }

    private ObservableCollection<ComboBoxModel> _items = new ObservableCollection<ComboBoxModel>();
    public ObservableCollection<ComboBoxModel> Items
    {
        get { return _items; }
        set { _items = value; }
    }

}

public class ComboBoxModel
{
    public string Name { get; set; }
    public string State { get; set; }
}

结果:

enter image description here enter image description here

关于c# - 在 ComboBoxItem 模板中使用 DisplayMemberPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283639/

相关文章:

c# - 如何在 ASP.NET Core 中设置正确的日期格式

c# - Polly 在 X 次重试后继续

c# - 无法使用 JRE 7u51 在 Internet Explorer 11 中运行 Java 小程序

wpf - 我可以在集合更改事件上回滚集合更改吗?

xaml - 我什么时候应该使用 Border over Grid?

javascript - 单击按钮时文件上传丢失内容

wpf - 如何访问数据模板中存在的控件

c# - WPF中干净而优雅的 View 模型

c# - Windows Phone 8 View 模型绑定(bind)

c# - WPF隐藏和显示按钮取决于datacontext的值