【问题标题】:Why does this code result in "The name does not exist in the current context" error?为什么此代码会导致“当前上下文中不存在该名称”错误?
【发布时间】:2012-09-28 00:44:14
【问题描述】:

下面的代码有问题:

<Window x:Class="ChangePage.PageSwitcher"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ChangePage"
    Title="ECE Showcase"
    WindowState="Maximized">

    <Window.Resources>
        <local:PageSwitcher x:Name="pageTransitionControl" TransitionType="SlideAndFade"/>
    </Window.Resources>

在文件 PageSwitcher.xaml.cs 后面的代码中,我有以下行:

pageTransitionControl.TransitionType = whatever;

但是这会导致以下错误:

当前上下文中不存在名称“pageTransitionControl”

我已经在互联网上搜索了几个小时,试图找出原因,但还没有弄清楚。 Build Action 设置为 Page,所有文件都保存了,我试过重建,PageSwitcher 在 ChangePage 命名空间中,PageSwitcher 有一个构造函数。

还有什么我做错了吗?

【问题讨论】:

    标签: c# wpf xaml code-behind


    【解决方案1】:

    您不能为资源分配名称。资源有键。

    <Window x:Class="ChangePage.PageSwitcher"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ChangePage"
        Title="ECE Showcase"
        WindowState="Maximized">
    
        <Window.Resources>
            <local:PageSwitcher x:Key="pageTransitionControl" TransitionType="SlideAndFade"/>
        </Window.Resources>
    

    然后在xaml.cs中:

    var pageTransitionControl = (PageSwitcher)Resources["pageTransitionControl"];
    pageTransitionControl.TransitionType = whatever;
    

    【讨论】:

      【解决方案2】:

      项目存在于窗口的资源中,而不是窗口本身

      您可以将其直接放置在 Window 本身而不是 Resources 中以使您的代码正常工作,或者将其分配给 x:Key 而不是 x:Name 并使用

      (PageSwitcher)this.Resources["pageTransitionControl"]
      

      【讨论】:

        【解决方案3】:

        您似乎无法直接访问后面代码中的资源。您可能需要使用 Resources["pageTransitionControl"] 来访问它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-12
          相关资源
          最近更新 更多