【发布时间】:2013-05-25 10:59:48
【问题描述】:
我在自定义控件中有以下DependencyProperty:
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..
}
运行良好,但如果我在自定义控件的“属性”面板中更改属性,则在运行时会引发异常:对象引用未设置为对象的实例。
编辑1:
忘记在帖子Ellipse el = nn.GetTemplateChild("PART_inner") as Ellipse;加一行代码
编辑2:
创建 BooleanToVisibilityConverter 并在 Generic.xaml 中使用 Binding 有效,但 HasConnectionChangedCallBack 方法现在为空/无用。
Visibility="{Binding HasConnection, Converter={StaticResource BooleanToVisibiltyConverter}, RelativeSource={RelativeSource TemplatedParent}}"
编辑3:
找到了一个可能的修复方法。首先调用属性回调方法,然后调用 OnApplyTemplate() 方法,因此不会再在 xaml 中引发异常或错误。
在 OnApplyTemplate() 我添加
if (this.HasConnection)
PART_inner.Visibility = System.Windows.Visibility.Visible;
else
PART_inner.Visibility = System.Windows.Visibility.Hidden;
【问题讨论】:
-
我认为那里没有足够的信息来真正回答您的问题。什么是网络节点?什么是 PART_Inner?
-
它是一个自定义控件。如果我不触摸 wpf 应用程序中的属性,则运行正常。如果在 xaml 中设置 HasConnection = "True",则在运行时会引发异常。
标签: c# .net wpf xaml dependency-properties