如何显示默认文字“ - 选择小组 - ”在WPF中的pageload上的组合框中? [英] How to display default text "--Select Team --" in combo box on pageload in WPF?
问题描述
在WPF应用程序中,在MVP应用程序中,我有一个组合框,为此我显示从数据库获取的数据。在添加到组合框之前,我要显示默认文本,例如
- 选择团队 - p>
,因此在页面加载时会显示,在选择文本时应清除文本,并显示项目。
正在从DB选择数据。我需要显示默认文本,直到用户从组合框中选择一个项目。
请指导我
您可以使用 IValueConverter
在没有任何代码的情况下执行此操作。
< Grid>
< ComboBox
x:Name =comboBox1
ItemsSource ={Binding MyItemSource}/>
< TextBlock
Visibility ={Binding SelectedItem,ElementName = comboBox1,Converter = {StaticResource NullToVisibilityConverter}}
IsHitTestVisible =False
Text =... Select Team .../>
< / Grid>
这里有你可以重用的转换器类。
public class NullToVisibilityConverter:IValueConverter
{
#region IValueConverter的实现
public object Convert(object value,类型targetType,对象参数,CultureInfo文化)
{
返回值== null? Visibility.Visible:Visibility.Collapsed;
}
public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
<转换器:NullToVisibilityConverter x:Key =NullToVisibilityConverter >
其中Converters是放置转换器类的地方。例如:
xmlns:Converters =clr-namespace:MyProject.Resources.Converters
这种方法的好处在于你的代码中不会重复代码。
In a WPF app, in MVP app, I have a combo box,for which I display the data fetched from Database. Before the items added to the Combo box, I want to display the default text such as
" -- Select Team --"
so that on pageload it displays and on selecting it the text should be cleared and the items should be displayed.
Selecting data from DB is happening. I need to display the default text until the user selects an item from combo box.
Please guide me
You can do this without any code behind by using a IValueConverter
.
<Grid>
<ComboBox
x:Name="comboBox1"
ItemsSource="{Binding MyItemSource}" />
<TextBlock
Visibility="{Binding SelectedItem, ElementName=comboBox1, Converter={StaticResource NullToVisibilityConverter}}"
IsHitTestVisible="False"
Text="... Select Team ..." />
</Grid>
Here you have the converter class that you can re-use.
public class NullToVisibilityConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
And finally, you need to declare your converter in a resource section.
<Converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
Where Converters is the place you have placed the converter class. An example is:
xmlns:Converters="clr-namespace:MyProject.Resources.Converters"
The very nice thing about this approach is no repetition of code in your code behind.
这篇关于如何显示默认文字“ - 选择小组 - ”在WPF中的pageload上的组合框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!