自定义UserControl中ContentPresenter中引用控件的NullReferenceException
本文关键字:NullReferenceException 控件 ContentPresenter UserControl 自定义 引用 | 更新日期: 2023-09-27 18:00:21
我创建了一个自定义UserControl(SlideControl),其中包含一个ContentPresenter(属性名:PageContent)。在我的页面上,我使用UserControl并向PageContent添加一些Xaml
其中一个控件有一个名称(testTb)。当我访问testTb时,它后面的代码在编译时被识别。在运行时,我得到一个NullReferenceException。
我能做什么?
这就是我所拥有的:
SlideControl.xaml:
<Canvas>
<!-- some style here I want to use on every app page (slide in menu) -->
<ContentPresenter Name="PageContentPresenter" />
</Canvas>
SlideControl.xaml.cs:
public object PageContent
{
get { return PageContentPresenter.Content; }
set { PageContentPresenter.Content = value; }
}
主页.xaml:
<helpers:BasePage x:Name="SlideControl">
<helpers:BasePage.PageContent>
<TextBox x:Name="testTb" />
</helpers:BasePage.PageContent>
</helpers:BasePage>
主页.xaml.cs:
public MainPage() {
InitializeComponent();
this.testTb.Text = "test text"; // NullReferenceException!!!
}
要达到testTb,必须执行
var testTb = (TextBox)PageContent.FindName("testTb");
//use testTb as you want.
这是因为testTb在不同的范围内
编辑:
如果你的XAML正是这样的:
<helpers:BasePage.PageContent>
<TextBox x:Name="testTb" />
</helpers:BasePage.PageContent>
那么您应该能够使用TextBox来完成以下操作:
var testTb = (TextBox)PageContent;
testTb.Text = "Whatever you want to do";
编辑
这是您需要的课程
MyVisualTreeHelper.cs
public static class MyVisualTreeHelper
{
public static T FindVisualChild<T>(this FrameworkElement obj, string childName) where T : FrameworkElement
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
FrameworkElement child = (FrameworkElement)VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T && child.Name == childName)
return (T)child;
else
{
T childOfChild = FindVisualChild<T>(child, childName);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
}
以下是使用方法:
var testTb = SlideControl.PageContent.FindVisualChild<TextBlock>("testTb");
if (testTb != null)
testTb.Text = "test2";