views:

19

answers:

2

I have a custom control. There is a Stack Panel with Button and TextBlock in generic.xaml:

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

Then I have

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); }
}
}

There is if with some logic in that happens after the button is clicked. How do I change the Text property of TextBloc? I thought that I can do something like this

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

But it always returns NullReferenceException (Object reference not set to an instance of an object.)

Should I use PropertyChangedCallback() on dependency property or what else do I need? I am missing something ;-)

+1  A: 

You're taking the wrong approach - instead of trying to push the text into the text block from the control's class, you need the text block to pull the value from the control's class. The main steps you need to do are:

  1. Change the type of the dependency property from TextBlock to string.

  2. Bind the Text property of the TextBlock in your control template to the dependency property using a TemplateBinding binding expression. Something along the lines of:

    <TextBlock Text="{TemplateBinding StatusText}" />

You can then simply set the text to be displayed to the property on your control.

Hope this helps...

Chris

Chris Anderson
A: 

You can type your question on google and find answer few times faster.

Samvel Siradeghyan
Have you noticed the results that Google finds is this question on SO? :-)
nubm