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>

我想以编程方式向 Window1.xaml.cs 添加一个TreeViewDockPanel但在 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"

我确定我只是错过了一些简单的事情。有任何想法吗?

4

3 回答 3

1

首先,您的 XAML 已损坏。</Grid>您有一个与打开 Grid 标签无关的额外内容。

我刚刚创建了一个项目,复制了你的 XAML 和代码,除了 captilisation 差异和修复额外的标签,我的工作正常。

我的完整 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);
    }
}

检查你所有的标签,确保你没有任何随机的无关标签漂浮在周围

于 2010-01-17T00:38:06.467 回答
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# 类、文本框和参考、Easy(?)“在当前上下文中不存在”

于 2010-01-16T18:21:02.743 回答
0

在进一步测试和故障排除后,我发现我无法引用添加到 Window1.xaml 的任何控件,而不仅仅是 DockPanel。要解决此问题,我必须将“MSBuild:Compile”添加到 Window1.xaml 文件属性中的自定义构建字段。

我不确定为什么我的项目中该字段为空白,但希望这将有助于其他遇到相同“错误”的人。

于 2010-01-17T02:07:41.360 回答