我正在创建一个自定义的WPF控件,它应该有几个内容插槽。
我希望用户能够使用字符串或FrameworkElement作为属性值,例如:
我知道WPF ContentControl可以实现这一点(接受字符串和其他元素),我知道它与TypeConverter属性有关(部分解释在这里),但是我尝试查看Reflector中的ContentControl、Label、TextBlock和其他控件,没有找到任何TypeConverter属性,并且谷歌搜索也没有帮助。
我最初尝试按照以下方式实现,但很明显它不知道如何将字符串转换为FrameworkElement,在控件初始化期间抛出异常:
然后我尝试这样黑它:
<!-- MyHeading is a string -->
<MyControl MyHeading="Hello World" />
<MyControl>
<!-- MyHeading is a FrameworkElement -->
<MyControl.MyHeading>
<Expander Header="Hello">
World
</Expander>
</MyControl.MyHeading>
</MyControl>
我知道WPF ContentControl可以实现这一点(接受字符串和其他元素),我知道它与TypeConverter属性有关(部分解释在这里),但是我尝试查看Reflector中的ContentControl、Label、TextBlock和其他控件,没有找到任何TypeConverter属性,并且谷歌搜索也没有帮助。
我最初尝试按照以下方式实现,但很明显它不知道如何将字符串转换为FrameworkElement,在控件初始化期间抛出异常:
public FrameworkElement Heading
{
get { return (FrameworkElement)GetValue(HeadingProperty); }
set { SetValue(HeadingProperty, value); }
}
// Using a DependencyProperty as the backing store for Heading. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeadingProperty =
DependencyProperty.Register("Heading", typeof(object), typeof(DialogControl), new UIPropertyMetadata(new FrameworkElement()));
然后我尝试这样黑它:
public object Heading
{
get { return (object)GetValue(HeadingProperty); }
set
{
if (value is string)
{
var tb = new TextBlock();
tb.Text = (string) value;
tb.FontSize = 20;
SetValue(HeadingProperty, tb);
}
else if (value is FrameworkElement)
{
SetValue(HeadingProperty, value);
} else
throw new ArgumentOutOfRangeException("Heading can take only string or FrameworkElement.");
}
}
// Using a DependencyProperty as the backing store for Heading. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HeadingProperty =
DependencyProperty.Register("Heading", typeof(object), typeof(DialogControl), new UIPropertyMetadata(null));
但它相当丑陋,仍无法实例化 :(。
有人知道如何做吗?感谢您的时间!