How to programmatically change DockPanel in WPF?

Note. Upon request, I added the complete code for my XAML and xaml.cs files.

In WPF, I created DockPanelthis:

<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>

I want to programmatically add TreeViewin DockPanel, but in Window1.xaml.cs I cannot get DockPanelby name and add to it:

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 above code returns the following error:

"The name 'ftpDock' does not exist in the current context"

I'm sure I just missed something simple. Any ideas?

+3
source share
3 answers

, - , Window1.xaml, DockPanel. , "MSBuild: Compile" " " Window1.xaml.

, , , , "".

0

-, XAML . </Grid>, 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);
    }
}

, ,

+1

In your xaml, do you have the correct class attribute for the window?

<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>

See here: WPF classes C #, TextBox and Reference, Easy (?) "Does not exist in the current context"

0
source

Source: https://habr.com/ru/post/1728748/


All Articles