无法从代码后面访问Metro XAML自定义控件

时间:2012-10-03 10:12:12

标签: c# xaml windows-8 windows-runtime winrt-xaml

尝试使用this问题的解决方案给我一个奇怪的问题。 (为方便起见,这里复制)

这是针对ListView吞下右键单击事件并阻止AppBar打开的问题的解决方案 - 继承ListView并覆盖OnRightTapped ListViewItem事件的类1}}:

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:重新提出问题以消除无关的问题。我也改变了标题以反映真正的问题。

1 个答案:

答案 0 :(得分:9)

我使用Name但应该使用x:Name。显然,自定义控件和用户控件需要在后面的代码中使用x:Name而不是Name

有关差异的更多信息:

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

相关问题