页面引用资源控件如何赋值

fxhome 2010-03-06 08:50:06
比如MainPage.xaml页引用了 有一个资源

<UserControl.Resources>
<local:UserControl1 x:Key="UserControl1DataSource" d:IsDataSource="True"/>
</UserControl.Resources>

//UserControl1 是一个用户控件

MainPage.xaml 还有一个内容控件

<ContentControl x:Name="contentControl" ></ContentControl>




然后我在MainPage.xaml.cs 的构造函数里写

UserControl1 obj = this.Resources["UserControl1DataSource"] as UserControl1;
contentControl.Content = obj;



为什么会显示 值不在预期的范围内?
注示:我就是不想写 UserControl1 obj=new UserControl1() 我想知道怎么把资源控件赋值 谢谢大家

...全文
46 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
jv9 2010-03-10
  • 打赏
  • 举报
回复
参考下面的代码:


<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300"
>
<UserControl.Resources>
<StackPanel x:Name="myStackPanel" x:Key="mykey"/>
</UserControl.Resources>
<StackPanel x:Name="LayoutRoot" Background="White">
</StackPanel>
</UserControl>
//Code behind
public partial class Page : UserControl
{
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
public Page()
{
InitializeComponent();
if(this.Resources.Contains("mykey"))
{
this.Resources.Remove("mykey");
}
LayoutRoot.Children.Add(myStackPanel);
myStackPanel.Children.Add(new Button { Content = "Hello World" });



}


8,735

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧