无法从代码隐藏访问地铁 XAML 自定义控件



试图使用这个问题的解决方案给了我一个奇怪的问题。(为方便起见,此处复制)

这是ListView吞下右键单击事件并阻止 AppBar 打开的问题的解决方案 - 继承ListView并重写 ListViewItemOnRightTapped事件的类:

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>

我已经在一个名为 CustomControls 的新命名空间中实现了指定的自定义控件,完全按照所述。我已将该命名空间添加到 MainPage.xaml

xmlns:CustomControls="using:CustomControls"

当我尝试在代码隐藏中引用"ItemsList"时,出现编译错误

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

我尝试过构建、重建、清理解决方案、关闭和重新打开解决方案、将类放在主项目命名空间下,但都无济于事。

总而言之,MainPage.cs 在 MainPage.xaml 上看不到自定义控件

更新2:改写了问题以删除不相关的问题。我还更改了标题以反映真正的问题。

我正在使用Name但应该使用x:Name.显然,自定义控件和用户控件需要使用x:Name而不是Name才能在代码隐藏中看到。

有关差异的更多信息,请单击此处:

在 WPF 中,x:Name 和 Name 属性之间有什么区别?

最新更新