Silverlight:从代码访问XAML控件
我在访问页面的XAML上定义的面板控件时遇到问题,XAML是这样定义的:Silverlight:从代码访问XAML控件,silverlight,user-controls,compiler-errors,Silverlight,User Controls,Compiler Errors,我在访问页面的XAML上定义的面板控件时遇到问题,XAML是这样定义的: <UserControl x:Class="PhoneBook.SilverlightMainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" mc:Ignorable="d" Wid
<UserControl
x:Class="PhoneBook.SilverlightMainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d" Width="400" Height="300" d:DesignWidth="993" d:DesignHeight="887">
<Grid x:Name="LayoutRoot" />
</UserControl>
var silverlightMainPage = new PhoneBook.SilverlightMainPage();
SomeMethod((silverlightMainPage.LayoutRoot);
我试着用这种方式来实例化它:
<UserControl
x:Class="PhoneBook.SilverlightMainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
mc:Ignorable="d" Width="400" Height="300" d:DesignWidth="993" d:DesignHeight="887">
<Grid x:Name="LayoutRoot" />
</UserControl>
var silverlightMainPage = new PhoneBook.SilverlightMainPage();
SomeMethod((silverlightMainPage.LayoutRoot);
我觉得奇怪的是,当我把点放在对象实例后面时,它实际上将LayoutRoot列为一个成员,但当我试图编译应用程序时,它说没有具有该名称的成员
你知道会发生什么吗
谢谢
编辑:我还尝试在SilverlightMainPage类上创建一个属性,该属性返回LayoutRoot元素,但它还表示该类不包含布局根的定义。您是否尝试从其他程序集访问SilverlightMainPage.LayoutRoot?在MainPage.g.i.cs文件中,LayoutRoot(以及XAML中定义的所有其他控件)标记为“内部”,即:
您可能希望尝试创建一个public属性,而不是一个内部属性,该属性执行FindName(“LayoutRoot”)并返回相应的控件。事实上,我发现了这个问题 我使用公司其他人开发的工具自动生成项目 我做了一些额外的测试,在项目中添加了一个新的UserControl,并尝试从代码隐藏中的属性访问LayoutRoot,结果成功了 然后将完全相同的代码复制到有问题的文件中(只是更改了类名),但它没有编译 然后我检查了项目文件,发现一个类似这样的部分:
public partial class SilverlightMainPage : UserControl
{
public SilverlightMainPage()
{
InitializeComponent();
}
}
<ItemGroup>
<Compile Include="SilverlightMainPage.xaml.cs">
<DependentUpon>SilverlightMainPage.xaml</DependentUpon>
</Compile>
</ItemGroup>
SilverlightMainPage.xaml
由于某种原因导致编译失败。
我删除了那个部分,现在一切正常
谢谢您的回答。尝试右键单击InitializeComponent()方法,然后选择“转到定义”。你看到LayoutRoot了吗?你无法访问的面板在哪里?你在哪里实例化主页?从App.xaml?你能提供SomeMethod()的代码吗?