@DeboshiR
Свободу разработчикам!!!

Как добавить в combobox текст, который не булет отображаться при выпадении?

Суть такая: есть combobox, в который записаны строки и добавлено свойство DropDownStyle: DropDownList. Надо чтобы пока combobox не активен в нём отображалась надпись "Выберите из списка". Вопрос: как такое реализовать?
  • Вопрос задан
  • 1424 просмотра
Пригласить эксперта
Ответы на вопрос 2
Rou1997
@Rou1997
У него свойство Text есть.
Ответ написан
andrewpianykh
@andrewpianykh
Если вопрос про WPF, то

Способ 1 (для людей) - Переопределяем Template для ComboBox как нам надо, вариантов много, в примере ниже с помощью триггера отображаем TextBlock (SelTextBlock) с текстом "Выберите из списка" если SelectedItem == null:

<Style TargetType="ComboBoxItem">
    ...
</Style>

<Style x:Key="ComboBoxToggleButtonStyle" TargetType="ToggleButton">
	...
</Style>

<Style x:Key="ComboBoxEditableTextBoxStyle" TargetType="TextBox">
	...
</Style>

<Style TargetType="ComboBox">
	<Setter Property="SnapsToDevicePixels" Value="True" />
	<Setter Property="OverridesDefaultStyle" Value="True" />
	...
	<Setter Property="Template">
		<Setter.Value>
			<ControlTemplate TargetType="ComboBox">
				<Grid>
					<ToggleButton x:Name="btn"
								  ClickMode="Press"
								  Focusable="false"
								  IsChecked="{Binding IsDropDownOpen,
													  Mode=TwoWay,
													  RelativeSource={RelativeSource TemplatedParent}}"
								  Style="{StaticResource ComboBoxToggleButtonStyle}">
						<Grid>
							<ContentPresenter x:Name="ContentSite"
											  HorizontalAlignment="Left"
											  VerticalAlignment="Center"
											  Content="{TemplateBinding SelectionBoxItem}"
											  ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
											  ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" />
							<TextBlock x:Name="SelTextBlock"
									   Text="Выберите из списка"
									   Visibility="Hidden" />
							<TextBox x:Name="PART_EditableTextBox"
									 IsReadOnly="{TemplateBinding IsReadOnly}"
									 Style="{StaticResource ComboBoxEditableTextBoxStyle}"
									 Visibility="Hidden" />
						</Grid>
					</ToggleButton>
					<Popup x:Name="PART_Popup"
						   AllowsTransparency="True"
						   Focusable="False"
						   IsOpen="{Binding IsDropDownOpen,
											RelativeSource={RelativeSource TemplatedParent}}"
						   Placement="Bottom"
						   PopupAnimation="Fade"
						   SnapsToDevicePixels="True">
						<Border MinWidth="{TemplateBinding ActualWidth}"
								MaxHeight="{TemplateBinding MaxDropDownHeight}"
								Background="White"
								BorderBrush="Lavender"
								BorderThickness="1,0,1,1"
								Padding="0,0,0,4">
							<ScrollViewer CanContentScroll="True"
										  HorizontalScrollBarVisibility="Auto"
										  VerticalScrollBarVisibility="Auto">
								<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
							</ScrollViewer>
						</Border>
					</Popup>
				</Grid>
				<ControlTemplate.Triggers>
					<Trigger Property="IsEditable" Value="True">
						<Setter TargetName="btn" Property="Tag" Value="Editable" />
						<Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />
						<Setter TargetName="ContentSite" Property="Visibility" Value="Hidden" />
						<Setter TargetName="SelTextBlock" Property="Visibility" Value="Hidden" />
					</Trigger>
					<Trigger Property="SelectedItem" Value="{x:Null}">
						<Setter TargetName="SelTextBlock" Property="Visibility" Value="Visible" />
					</Trigger>
					...
				</ControlTemplate.Triggers>
			</ControlTemplate>
		</Setter.Value>
	</Setter>
</Style>


Способ 2 (для извращенцов) - Накладываем TextBlock с текстом "Выберите из списка" поверх ComboBox и с помощью Binding и кастомного конвертера ObjectToVisibilityConverter отображаем его если SelectedItem == null:

...
<Window.Resources>
	<local:ObjectToVisibilityConverter x:Key="ObjectToVisibilityConverter" />
</Window.Resources>
...
<Grid>
	<TextBlock Margin="4,0,0,0"
			   HorizontalAlignment="Left"
			   VerticalAlignment="Center"
			   Panel.ZIndex="1000"
			   Text="Выберите из списка"
			   Visibility="{Binding ElementName=CmbBox,
									Path=SelectedItem,
									Converter={StaticResource ObjectToVisibilityConverter}}" />
	<ComboBox x:Name="CmbBox" Width="200" />
</Grid>


public class ObjectToVisibilityConverter : IValueConverter
{
	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
	{
		return value == null ? Visibility.Visible : Visibility.Hidden;
	}

	public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
	{
		throw new NotImplementedException();
	}
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы