WPF - 格式化ComboBox的显示项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF - 格式化ComboBox的显示项相关的知识,希望对你有一定的参考价值。
我已经格式化了一个ComboBox来显示每个项目的详细信息,请不要将设计视为最终,这只是一个例子:
但正如您所看到的,显示的项目(带有箭头的框内)已损坏:
所以我也需要格式化该组件,以便在该框中仅显示Server值。我试图找到正确的元素,甚至设法找到重新格式化整个组合框的方法,但无法为该框内的数据显示添加模板。
<ComboBox x:Name="cboSourcemysql" Grid.Column="1" Margin="5,0,5,0" ItemsSource="{Binding OdbcDataSources, Mode=TwoWay}" Grid.Row="1" >
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="50" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Label Content="Server:" Grid.Column="0" Grid.Row="0" />
<TextBlock Text="{Binding Server}" VerticalAlignment="Center" Grid.Column="1" Grid.Row="0" />
<Label Content="Driver:" Grid.Column="0" Grid.Row="1" />
<TextBlock Text="{Binding Driver}" VerticalAlignment="Center" Grid.Column="1" Grid.Row="1" />
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
答案
从文章WPF Combobox: Different template in textbox and drop-downlist我认为你可以使用以下风格
<ComboBox
x:Name="cboSourceMySql"
Grid.Column="1" Margin="5,0,5,0"
ItemsSource="{Binding OdbcDataSources, Mode=TwoWay}"
Grid.Row="1" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Server}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Border
x:Name="Bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel Orientation="Vertical">
<Label Content="{Binding Server}" />
<Label Content="{Binding Driver}" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
以上是关于WPF - 格式化ComboBox的显示项的主要内容,如果未能解决你的问题,请参考以下文章
WPF IsEditable=true 填充了对象的 ComboBox 将 ToString() 显示为选定项