簡體   English   中英

為什么此代碼會導致“名稱在當前上下文中不存在”錯誤?

[英]Why does this code result in “The name does not exist in the current context” error?

我在使用以下代碼時遇到麻煩:

<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”在當前上下文中不存在

我已經在Internet上搜索了幾個小時,試圖找到原因,但是還沒有找到答案。 Build Action設置為Page,所有文件都保存,我嘗試過重建,PageSwitcher在ChangePage命名空間中,而PageSwitcher具有構造函數。

我在做別的事情嗎?

您不能為資源分配名稱。 資源具有密鑰。

<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;

該項目存在於窗口的資源中,而不存在於窗口本身中

您可以將其直接放置在Window本身中,而不是放置在Resources中以使代碼正常工作,或者將其分配給x:Key而不是x:Name並使用

(PageSwitcher)this.Resources["pageTransitionControl"]

似乎您無法直接訪問后面代碼中的資源。 您可能需要使用Resources [“ pageTransitionControl”]進行訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM