这是ComboBox
ItemTemplate
:
<DataTemplate x:Key="DataTemplate2">
<Grid Background="AliceBlue" Height="30">
<TextBlock Text="{Binding Content}" Foreground="Lime"></TextBlock>
</Grid>
</DataTemplate>
我想在上面的Texblock.TextTrimming
使用TextBlock
。这个TextBlock
将是屏幕上的ComboBoxItem
,但我不知道在TextBlockText
放置什么。我应该绑定什么?
我通常会看到他们放置的示例:Text={Binding CustomClass.CustomProperty}
,但我需要将其设为通用。因此它适用于应用程序的每个ComboBox
。
我可以在文字中添加什么?
拜托,我试试了4个小时。
答案 0 :(得分:1)
如果想要它是通用的,只需使用{Binding}
示例:
<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>
代码:
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; }
}
}
结果:
如果您使用的是自定义对象,则可以覆盖ToString
方法,以便在组合框中显示您想要的内容
实施例
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:
与上述相同
结果: