问题
I'm trying to create an ItemTemplate for a ListBox programmatically but it doesn't work. I know in XAML I can have something like:
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But when I'm trying to have the above result programmatically I face a problem which is binding the TextBox.TextProperty
:
var textblock = new FrameworkElementFactory(typeof(TextBlock));
// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;
Please help me on this issue. I couldn't find anything on the web about it.
Thanks in advance.
回答1:
Try use dot .
in Binding, this is the equivalent of {Binding}
.
Example:
XAML
<Window x:Class="MyNamespace.MainWindow"
...
Loaded="Window_Loaded">
<ListBox Name="MyListBox" ... />
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
var template = new DataTemplate();
template.VisualTree = textBlockFactory;
MyListBox.ItemTemplate = template;
}
}
回答2:
Try this, by binding the "listbox" with ItemsSource and specify the datatemplate below like if you want to bind name then just write {Binding Name}
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
来源:https://stackoverflow.com/questions/23079496/create-itemtemplate-for-listbox-in-code-beind-in-wpf