我的代码生成的ListBox的项目未显示任何内容

时间:2019-07-04 01:00:25

标签: c# wpf listbox code-behind listboxitem

我在WPF中有一个代码生成的窗口(使用dotnet core 3.0预览版6),并且在运行我的应用程序时,它获取了正确的数据,并且在ListBox中填充了正确的行数,但是它们都不包含值

这是我正在做的一个测试项目,以熟悉代码生成的WPF,因为它是我们正在进行的下一个项目所需要的;我本来希望使用XAML,但是我的领导说这会带来代码可重用性的问题。

首先,我确保使用的对象是“干净的”(我的实体是为Linq2db设置的,所以我确保属性不能成为罪魁祸首),然后我测试了绑定(只是得到了“错误40英寸-错误代码,但这与主要问题无关)。我还更改了框的类型,但这无济于事(DataGrid确实可以工作,但这不是我在视觉效果中寻找的东西)。

rr

结果窗口的图像,(从示例代码中删除了一些样式代码以减少噪音) enter image description here

1 个答案:

答案 0 :(得分:0)

基于Flithor's的评论,我这样做了,并且效果很好:

private DataTemplate GetDataTemplate()
    {
        var dataTemplate = new DataTemplate(typeof(MessageDto));

        FrameworkElementFactory stackPanelFactory = new FrameworkElementFactory(typeof(StackPanel));
        stackPanelFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

        FrameworkElementFactory timestamp = new FrameworkElementFactory(typeof(Label));
        timestamp.SetBinding(Label.ContentProperty, new Binding("Timestamp"));
        FrameworkElementFactory from = new FrameworkElementFactory(typeof(Label));
        from.SetBinding(Label.ContentProperty, new Binding("From"));
        FrameworkElementFactory message = new FrameworkElementFactory(typeof(Label));
        message.SetBinding(Label.ContentProperty, new Binding("Message"));
        stackPanelFactory.AppendChild(timestamp);
        stackPanelFactory.AppendChild(from);
        stackPanelFactory.AppendChild(message);

        dataTemplate.VisualTree = stackPanelFactory;

        return dataTemplate;
    }