它仅在运行时有效。如果我将 new InputNodeRed() 绑定到 MyNode 的 Node 控件,则仅在程序运行时而不是在设计时显示静态资源。我究竟做错了什么。(详见转换器代码注释)
自定义控制节点
public class Node : Control
{
static Node()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Node), new FrameworkPropertyMetadata(typeof(Node)));
}
public BaseData.Node MyNode
{
get { return (BaseData.Node)GetValue(MyNodeProperty); }
set { SetValue(MyNodeProperty, value); }
}
public static readonly DependencyProperty MyNodeProperty =
DependencyProperty.Register("MyNode", typeof(BaseData.Node), typeof(Node), new PropertyMetadata(null));
}
}
节点转换器
public class NodeTypeToDataTemplateConverter :IValueConverter
{
public DataTemplate RedNode { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
//if(value == null) //binding new InputNodeRed(), at design time value == null
// return null;
if (value is BaseData.InputNodeRed || value is BaseData.OutputNodeRed)
return RedNode;
return null;
}
}
我放这个代码if(value == null) return null;
只是为了检查值是否为空,它在设计时返回空。
节点模板
<local:NodeTypeToDataTemplateConverter x:Key="NodeTypeConverter"
RedNode="{StaticResource RedNode}" />
<Style TargetType="{x:Type local:Node}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Node}">
<ContentPresenter ContentTemplate="{Binding MyNode, Converter={StaticResource NodeTypeConverter}, RelativeSource={RelativeSource TemplatedParent}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
数据类
abstract public class Node { }
abstract public class InputNode : Node { }
abstract public class OutputNode : Node { }
public class OutputNodeRed : OutputNode { }
public class InputNodeRed : InputNode { }
明显地约束工作,但不是在设计时。