简体   繁体   English

无法将模型绑定到TreeView

[英]Unable to bind model to TreeView

This is a logging project, the Title provides the name of the item and the message logs each stage. 这是一个日志记录项目,“标题”提供项目的名称,消息记录每个阶段。 Therefore, there are many Messages for each Title. 因此,每个标题有很多消息。

For the purpose of asking a question, I am simplifying my objects. 为了提出问题,我正在简化我的对象。

My Log class has 2 properties. 我的Log类具有2个属性。

List<LogDetails>
string Title

And my LogDetails class has 1 property: 我的LogDetails类具有1个属性:

string Message

I am not able to bind the Message to my XAML. 我无法将邮件绑定到我的XAML。 The Title binds as desired. 标题根据需要绑定。

My xaml code: 我的XAML程式码:

<Window x:Class="BackUps.Logging.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:myData="clr-namespace:BackUps.Logging"
        Title="MainWindow"
        Height="350"
        Width="525">
  <Grid>
    <TreeView ItemsSource="{Binding}">
      <TreeView.ItemTemplate>
        <HierarchicalDataTemplate DataType="{x:Type myData:Log}"
                                  ItemsSource="{Binding LogDetailsList}">
          <TextBlock Text="{Binding Title}" />
          <HierarchicalDataTemplate.ItemTemplate>
            <DataTemplate DataType="{x:Type myData:LogDetails}">
              <StackPanel>
                <TextBlock Text="{Binding Message}" />
              </StackPanel>
            </DataTemplate>
          </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
      </TreeView.ItemTemplate>
    </TreeView>
  </Grid>

and my code behind 和我的代码后面

  public MainWindow(List<Log> logs)
    {
        InitializeComponent();
        this.DataContext = logs;
    }

My result is (where you can see the missing entries): 我的结果是(您可以在其中看到丢失的条目):

在此处输入图片说明

This is the Auto's window, which shows the object I'm trying to bind. 这是“自动”窗口,其中显示了我要绑定的对象。

在此处输入图片说明

What have I missed or doing wrong? 我错过了什么或做错了什么?

I had a similar problem in the past, and fixed it by (completely) changing the xaml to the form: 过去我也遇到过类似的问题,并通过(完全)将xaml更改为以下形式来解决此问题:

<Grid>
  <TreeView ItemsSource="{Binding}">
    <TreeView.Resources>
      <HierarchicalDataTemplate DataType="{x:Type myData:Log}"
                                ItemsSource="{Binding LogDetailsList}">
        <TextBlock Text="{Binding Title}" />
      </HierarchicalDataTemplate>
      <HierarchicalDataTemplate DataType="{x:Type myData:LogDetails}>
                        <TextBlock Text="{Binding Message}" />
      </HierarchicalDataTemplate>
    </TreeView.Resources>
  </TreeView>
</Grid>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM