如何从代码后面更改TextBlock文本?

时间:2010-10-09 22:14:51

标签: silverlight silverlight-4.0

我有自定义控件。在generic.xaml中有一个带有Button和TextBlock的Stack Panel:

<StackPanel>
<TextBlock x:Name="StatusText" />
</StackPanel>

然后我

public class MyClass : Control
{
// Constructor etc.

public static readonly DependencyProperty StatusTextProperty = DependencyProperty.Register("StatusText", typeof(TextBlock), typeof(MyClass), null);

public TextBlock StatusText
{
get { return (TextBlock)this.GetValue(StatusTextProperty); }
set { SetValue(StatusTextProperty, value); }
}
}

如果在点击按钮后出现某些逻辑,则会出现这种情况。 如何更改TextBloc的Text属性? 我以为我可以做这样的事情

StatusText.SetValue(TextBlock.TextProperty, "Some text here.");

但它总是返回NullReferenceException(对象引用未设置为对象的实例。)

我应该在依赖属性上使用PropertyChangedCallback()还是我还需要什么?我错过了一些东西; - )

2 个答案:

答案 0 :(得分:1)

你采取了错误的方法 - 而不是试图文本推送到控件类的文本块中,你需要文本块来值来自对照班。您需要做的主要步骤是:

  1. 将依赖项属性的类型从TextBlock更改为string。

  2. 使用TemplateBinding绑定表达式将控件模板中TextBlock的Text属性绑定到依赖项属性。有点像:

    &lt; TextBlock Text =“{TemplateBinding StatusText}”/&gt;

  3. 然后,您只需将要显示的文本设置为控件上的属性即可。

    希望这会有所帮助......

    克里斯

答案 1 :(得分:-6)

您可以在Google上输入您的问题并快速找到答案几次。

相关问题