我正在尝试以编程方式为ListBox创建ItemTemplate,但是它不起作用。我知道在XAML中我可以有类似以下内容:

<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>


但是,当我尝试以编程方式获得上述结果时,我遇到了绑定TextBox.TextProperty的问题:

var textblock = new FrameworkElementFactory(typeof(TextBlock));

// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;


请帮我解决这个问题。我在网上找不到任何有关它的信息。

提前致谢。

最佳答案

尝试在Binding中使用点.,这等效于{Binding}

例:

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;
    }
}

关于c# - 在WPF中的代码隐藏中为ListBox创建DataTemplate,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23079496/

10-10 18:13