可以忽略System.Windows.Data错误:4?

时间:2018-06-21 16:36:56

标签: c# wpf treeview

我有以下代码,用于查询数据库以按组组织的服务器列表。它可以工作,但是在控制台中出现错误:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment; DataItem=null; target element is 'TreeViewItem' (Name=''); target property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'TreeViewItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

我的代码是:

        TreeViewItem treeItem = null;

        var serverGroupList = ServerDB.ExecuteDB("SELECT * FROM server_groups");

        var json = JsonConvert.SerializeObject(serverGroupList);
        dynamic dynJson = JsonConvert.DeserializeObject(json);
        foreach (var item in dynJson)
        {
            treeItem = new TreeViewItem();
            treeItem.Header = item.name;

            var serverListResults = ServerDB.ExecuteDB("SELECT * FROM servers WHERE group_id = " + item.id);
            var serversJSON = JsonConvert.SerializeObject(serverListResults);
            dynamic servers = JsonConvert.DeserializeObject(serversJSON);

            foreach (var server in servers)
            {
                Console.WriteLine("Adding: " + server.name);
                treeItem.Items.Add(new TreeViewItem() { Header = server.name });


            }

        }
        ServerList.Items.Add(treeItem);

如果我将最后一行ServerList.Items.Add(treeItem);向上移动到大括号内一行,则错误消失了,但最终我还是重复了同一组。

XAML代码没有什么特别的

<TreeView HorizontalAlignment="Left" Height="261" Margin="21,15,0,0" VerticalAlignment="Top" Width="132"  Name="ServerList">

        </TreeView>

我应该忽略它,因为它正在工作,还是会再次困扰我?

0 个答案:

没有答案