I have the following DependencyProperty
in a custom control:
public bool HasConnection
{
get { return (bool)GetValue(HasConnectionProperty); }
set { SetValue(HasConnectionProperty, value); }
}
public static readonly DependencyProperty HasConnectionProperty =
DependencyProperty.Register(
"HasConnection",
typeof(bool),
typeof(NetworkNode),
new FrameworkPropertyMetadata(
false,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(HasConnectionChangedCallBack)));
private static void HasConnectionChangedCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NetworkNode nn = (NetworkNode)d;
Ellipse el = nn.GetTemplateChild("PART_inner") as Ellipse;
if (el.PART_inner.Visibility == ...) <-- exception el is null
//..code..
}
Runs fine, but if I change the property in Properties panel of my custom control, at run time throws an exception: Object reference not set to an instance of an object.
Edit1:
Forgot to add one line of code in the post Ellipse el = nn.GetTemplateChild("PART_inner") as Ellipse;
Edit2:
Creating a BooleanToVisibilityConverter and using Binding in Generic.xaml works, but the HasConnectionChangedCallBack method is now empty/useless.
Visibility="{Binding HasConnection, Converter={StaticResource BooleanToVisibiltyConverter}, RelativeSource={RelativeSource TemplatedParent}}"
Edit3:
Found a posible fix. The property callback method is called first then the OnApplyTemplate() method, so no more exceptions thrown or error in xaml.
In OnApplyTemplate() I add
if (this.HasConnection)
PART_inner.Visibility = System.Windows.Visibility.Visible;
else
PART_inner.Visibility = System.Windows.Visibility.Hidden;