Home > Enterprise >  cannot reference WPF controls in code-behind in a different page
cannot reference WPF controls in code-behind in a different page

Time:10-03

I made a project where it was one page only, then after I made everything decided to go back in and make a second page, which was a huge mistake because now I have 50 compiler errors. In my new page's code behind, I cannot access any control by name and the page cannot access any event handlers in the code-behind. Here is an example:

Autoclicker.xaml

<Page x:Class="_1337clicker.Pages.Autoclicker"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:local="clr-namespace:_1337clicker.Pages"
      mc:Ignorable="d" 
      d:DesignHeight="450" d:DesignWidth="800"
      Title="Autoclicker">

    <Grid>
        <Button Name="hi"/>
    </Grid>
</Page>

Autoclicker.xaml.cs

using System.Windows;
using System.Windows.Controls;

namespace _1337clicker
{
    public partial class Autoclicker : Page
    {
        public Autoclicker()
        {
             hi.Content = "hello world"; //The name "hi" does not 
                                         //exist in the current context
        }
    }
}

CodePudding user response:

I think you just messed up classname/namespace.

Check in XAML:

x:Class="_1337clicker.Pages.Autoclicker"

This will generate all the variables related to controls in a class called Autoclicker in a namespace of _1337clicker.Pages

but then, your code-behind class is:

namespace _1337clicker    // <---- DIFFERENT NAMESPACE
{
    public partial class Autoclicker : Page

You ended up with two 'Autoclicker' classes, one generated from XAML, other writen by you. Correct the namespaces and class names so they are identical, and try again. Generated code will end up in the same class as codebehind, and probably all such errors will go away.

EDIT: also what Joe noticed, it should be x:Name. Just 'Name' will let you find the control with tree walking and/or find-by-name tools, but probably won't generate a variable for code-behind.

  • Related