This is the Custom Control With Dependency Property
[TemplatePart(Name = "PART_outter", Type = typeof(Ellipse))]
[TemplatePart(Name = "PART_inner", Type = typeof(Ellipse))]
[TemplatePart(Name = "PART_canvas", Type = typeof(Canvas))]
public class NetworkNode : Control
{
static NetworkNode()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NetworkNode), new FrameworkPropertyMetadata(typeof(NetworkNode)));
}
private Canvas PART_canvas;
private Ellipse PART_outter;
private Ellipse PART_inner;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
PART_canvas = this.GetTemplateChild("PART_canvas") as Canvas;
PART_outter = this.GetTemplateChild("PART_outter") as Ellipse;
PART_inner = this.GetTemplateChild("PART_inner") as Ellipse;
}
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,
new PropertyChangedCallback(callBack)));
private static void callBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
NetworkNode nn = (NetworkNode)d;
if (nn.Template == null) return;
Ellipse el = nn.GetTemplateChild("PART_inner") as Ellipse;
var test = el.Visibility;
switch (test)
{
case Visibility.Collapsed:
break;
case Visibility.Hidden:
el.Visibility = Visibility.Visible;
break;
case Visibility.Visible:
el.Visibility = Visibility.Hidden;
break;
default:
break;
}
}
}
If i do HasConnection="False" no problem at all, it compile and runs fine.
The problem is, "i think", when I do HasConnection="True" in xaml, the dependency prop detects the value change and call the method callBack, but the custom control isnt yet instantiated and therefore the null exception. With binding problem solved. but i wanna do it in code behind.
<ioncontrolslibrary:networknode x:name="uiNode" horizontalalignment="Left" margin="59,427,0,0" verticalalignment="Top" hasconnection="True" xmlns:x="#unknown" xmlns:ioncontrolslibrary="#unknown" />