Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Metro XAML custom control cannot be accessed from code behind

Trying to use the solution to this question gives me a weird problem. (Replicated here for convenience)

This is a solution for an issue with ListView swallowing the right-click event and preventing the AppBar from opening - A class which inherits ListView and overrides the OnRightTapped event of ListViewItem:

public class MyListView : ListView
{
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new MyListViewItem();
    }
}

public class MyListViewItem : ListViewItem
{
    protected override void OnRightTapped(Windows.UI.Xaml.Input.RightTappedRoutedEventArgs e)
    {
        base.OnRightTapped(e);
        e.Handled = false; // Stop 'swallowing' the event
    }
}

<CustomControls:MyListView
    x:Name="ItemsList"
    ...
    SelectionMode="Single"
    RightTapped="MyListView_RightTapped">
</CustomControls:MyListView>

I have implemented a custom control as specified, in a new namespace called CustomControls, exactly as described. I've added that namespace to MainPage.xaml

xmlns:CustomControls="using:CustomControls"

When I then try and reference 'ItemsList' in code behind, I get a compile error

The name 'ItemsList' does not exist in the current context

I've tried building, rebuilding, cleaning the solution, closing and reopening the solution, putting the classes under the main project namespace, all to no avail.

To summarise, MainPage.cs cannot see a Custom Control on MainPage.xaml

UPDATE 2: Reworded the question to remove irrelevant issues. I've also changed the title to reflect the real issue.

like image 399
roryok Avatar asked Jan 15 '23 10:01

roryok


1 Answers

I was using Name but should have been using x:Name. Apparently custom controls and user controls need to use x:Name rather than Name to be seen in code behind.

More info on the difference here:

In WPF, what are the differences between the x:Name and Name attributes?

like image 120
roryok Avatar answered Feb 15 '23 14:02

roryok