[英]How to Bind ComboboxItem Text to Combobox Text?
This is a ComboBox
ItemTemplate
: 这是一个
ComboBox
ItemTemplate
:
<DataTemplate x:Key="DataTemplate2">
<Grid Background="AliceBlue" Height="30">
<TextBlock Text="{Binding Content}" Foreground="Lime"></TextBlock>
</Grid>
</DataTemplate>
I want to use Texblock.TextTrimming
at the TextBlock
above. 我想在上面的
TextBlock
使用Texblock.TextTrimming
。 This TextBlock
will be the ComboBoxItem
at screen, but I don't know what to put at TextBlockText
. 此
TextBlock
将在屏幕上显示为ComboBoxItem
,但我不知道在TextBlockText
放置什么。 What should I bind? 我应该绑定什么?
I usually see examples where they put: Text={Binding CustomClass.CustomProperty}
, but I need to make it generic. 我通常会看到放置它们的示例:
Text={Binding CustomClass.CustomProperty}
,但是我需要使其通用。 So it will work for every ComboBox
of the application. 因此它将适用于应用程序的每个
ComboBox
。
What can I put at Text? 我可以在Text上输入什么?
Please, I am trying this for 4 hours. 请,我正在尝试4个小时。
If tou want it to be generic just use {Binding}
如果您希望它是通用的,请使用
{Binding}
Example: 例:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="130" Width="167" Name="UI" >
<Grid >
<ComboBox ItemsSource="{Binding ElementName=UI, Path=Items}" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="comboBox1" VerticalAlignment="Top" Width="120" >
<ComboBox.ItemTemplate>
<DataTemplate>
<Grid Background="AliceBlue">
<TextBlock Text="{Binding}" Foreground="Lime"/>
</Grid>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
Code: 码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Items.Add("Stack");
Items.Add("Overflow");
}
private ObservableCollection<string> _items = new ObservableCollection<string>();
public ObservableCollection<string> Items
{
get { return _items; }
set { _items = value; }
}
}
Result: 结果:
And if you are using a custom object you can just override the ToString
method so it displays what you want in the combobox 而且,如果您使用的是自定义对象,则可以覆盖
ToString
方法,以便在组合框中显示所需的内容
Example 例
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Items.Add(new CustomObject { Name = "Stack" });
Items.Add(new CustomObject { Name = "Overflow" });
}
private ObservableCollection<CustomObject> _items = new ObservableCollection<CustomObject>();
public ObservableCollection<CustomObject> Items
{
get { return _items; }
set { _items = value; }
}
}
public class CustomObject
{
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
Xaml: Xaml:
Same as above 同上
Result: 结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.