【问题标题】:FindName returns null查找名称返回 null
【发布时间】:2014-03-13 15:56:01
【问题描述】:

我正在尝试从另一个 C# 类中获取具有自己名称的 XAML 元素,但它总是返回 null,为什么?

这是带有 C# 类的目标 XAML:

XAML:
<Page
    x:Class="myApp.SubSpace.SomePage"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:myApp.SubSpace"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid x:Name="target">
    </Grid>
</Page>

C#:
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace myApp.SubSpace 
{
    public sealed partial class SomePage : Page
    {
        public SomePage()
        {
            InitializeComponent();
        }
    }
}

这是它给我一个空结果的代码:

using myApp.SubSpace;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace myApp.Core
{
    public class Main
    {
        private Grid target;
        public Main() {
            FrameworkElement page = new SomePage();
            this.target = (Grid)page.FindName("target");
        }
    }
}

代码非常简化,但非常重要的东西都在那里。调用新的Main 对象后,其target 字段为空。怎么了?

提前致谢!

【问题讨论】:

  • 你要那个干什么?
  • @HighCore 正如我所说,代码非常简化,但之后必须编辑target 对象。
  • FindName returning null 的可能重复项
  • 您将 XAML 分配给您的类 SomePage() 的位置?我在 SomePage 中看不到任何涉及 XAML 的代码。
  • 对象必须被“编辑”——这就是DataBinding 的用途。 强烈建议您在基于 XAML 的技术中使用适当的 DataBinding,而不是使用传统的过程代码方法。这是因为可视化树是一个复杂的结构,处理起来太麻烦了。

标签: c# wpf xaml windows-store-apps


【解决方案1】:

我有一个基于Tips and Tricks for C# Metro developer: How to find a XAML control by its name 中的代码 sn-p 的辅助静态类。它还没有让我失望。

【讨论】:

    【解决方案2】:
    Grid myGrid= 
    this.FindName("target") as Grid;
    

    【讨论】:

      【解决方案3】:

      我意识到在 OP 的代码中并非如此,但我遇到了同样的错误(从 FindChild 返回 null),对我来说,这是在调用 InitializeComponent() 之前在 Page 的构造函数中调用 FindChild 的问题。在查看孩子之前,请确保一切都已初始化并准备就绪。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多