【问题标题】:Can't access Windows 8 Store user control from code无法从代码访问 Windows 8 应用商店用户控件
【发布时间】:2013-07-11 15:03:51
【问题描述】:

我正在编写一个 Windows 8 应用商店应用程序,并在其中设计了自己的用户控件。

这是我的用户控件的代码(这是一个虚拟控件,但存在问题):

<UserControl
    x:Class="Windows8StoreTest.TestUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows8StoreTest"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Width="70"
    Height="40">

    <StackPanel>
        <Button Content="Hello" Foreground="Pink" BorderBrush="Pink"/>
    </StackPanel>
</UserControl>

我已将用户控件放到我的页面上并为其命名:

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

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <local:TestUserControl Name="testControl"/>
    </Grid>
</Page>

但是,当我转到后面的代码时,我无法访问该名称的控件。它似乎不存在!奇怪的是,控件在 MainPage 类的 InitializeComponent() 方法中不存在,这就是它存在的原因。

我的用户控件缺少什么?

我正在使用 Windows 8 应用商店、XAML、c#。

提前致谢

【问题讨论】:

  • 它应该可以工作。您能否分享更多信息以缩小问题范围?

标签: c# windows-8 user-controls winrt-xaml


【解决方案1】:

尝试使用这个:

<local:TestUserControl x:Name="testControl"/>

应该可以...

【讨论】:

    【解决方案2】:

    你好,我不知道出了什么问题,但它应该可以工作。我刚刚做了一个示例。我把它放在这里希望你也这样做了。

    <Page
    x:Class="App12.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App12"
    
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <local:MyUserControl1 x:Name="hellousercontrol"  />
    </Grid>
    

    在我的 mainpage.cs.. 我只是这样使用它..

    public MainPage()
        {
            this.InitializeComponent();
    
            hellousercontrol.Height = 100;
    }
    

    还有这个..已经构建了您的解决方案?

    【讨论】:

    • 控件似乎没有添加到 InitializeComponent 方法和其中的类中!?我将更新我的问题以包含完整的代码
    【解决方案3】:

    我在 c++ 环境中遇到了同样的问题。我观察到,我的类中没有默认构造函数,只要添加了默认构造函数,我就可以通过 XAML 文件在我的项目中使用定义的 UserControl。但是,如果没有默认构造函数,我可以在 c++ 代码中使用它。

    【讨论】:

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