如何在WPF中编程更改DockPanel?

3

注意:根据要求,我已添加了我的XAML和xaml.cs文件的完整代码。

在WPF中,我创建了一个DockPanel,如下所示:

<Window x:Class="RealEditor.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        Title="RealEditor" Height="500" Width="700">
    <DockPanel>
        <GridSplitter Grid.Column="1" Width="4" HorizontalAlignment="Left"/>
        <DockPanel x:Name="ftpDock" Grid.Row="1" Grid.Column="1"></DockPanel>
    </Grid>???
    </DockPanel>
</Window>

我希望通过编程方式将一个 TreeView 添加到 DockPanel,但是在 Window1.xaml.cs 文件中,我无法通过名称获取到 DockPanel 并将其添加到其中:

namespace RealEditor
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
      TreeViewItem mytreeView = new TreeViewItem();
      ftpDock.Children.Add(myTreeView);
    }
  }
}

上述代码返回以下错误:
"The name 'ftpDock' does not exist in the current context"

我相信我只是错过了一些简单的东西。有什么想法吗?

1
展示更多的代码,XAML和后台代码。 - Aviad P.
3个回答

1

首先,你的XAML代码有问题。你多了一个</Grid>标签,而且没有对应的开头标签。

我刚刚创建了一个项目,复制了你的XAML和代码,除了大小写不同和修复额外的标签之外,我的代码可以正常工作。

我的完整XAML代码:

<Window x:Class="WPFTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <DockPanel>
        <GridSplitter Grid.Column="1" Width="4" HorizontalAlignment="Left"/>
        <DockPanel x:Name="ftpDock" Grid.Row="1" Grid.Column="1"></DockPanel>
    </DockPanel>
</Window>

代码后台:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        TreeViewItem mytreeView = new TreeViewItem();
        ftpDock.Children.Add(mytreeView);
    }
}

检查所有标签,确保没有任何随意的杂乱标签漂浮在周围


0
在你的XAML中,窗口的类属性是否正确?
<Window x:Class="YourAssemblyName.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
            <DockPanel Grid.Row="1" x:Name="ftpDock" Grid.Column="1"></DockPanel>
    </Grid>
</Window>

请看这里:WPF C# 类、文本框和引用,易错(?)“在当前上下文中不存在”

是的,在XAML中,class属性是正确的,我正在尝试访问Window1: Window类中的DockPanel。 - CheapDevotion
在Window1类的哪个位置?你的XAML具体是什么样子?因为像上面我发布的.Window1文件会允许你在代码背后访问ftpDock。没有更多信息,无法知道如何解决你的问题。 - Eric Dahlvang

0
经过进一步的测试和故障排除,我发现无法引用添加到Window1.xaml的任何控件,而不仅仅是DockPanel。为了解决这个问题,我不得不在Window1.xaml文件属性的自定义构建字段中添加“MSBuild:Compile”。
我不确定为什么我的项目中该字段为空,但希望这可以帮助其他遇到同样“错误”的人。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接