指定 Xaml 中的开始和结束标记之间的属性 [英] Specify which Property goes between the opening and closing tag in Xaml

查看:26
本文介绍了指定 Xaml 中的开始和结束标记之间的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Xaml

<Grid>
    <TextBox>Text</TextBox>
    <Button>Content</Button>
</Grid>

它将设置

  • TextBox 的文本属性 (仅限 WPF)
  • 按钮的内容属性
  • 网格的子属性

但是这是如何指定的呢?您如何指定 Xaml 中开始标记和结束标记之间的属性?
这是由依赖属性中的某些元数据设置的还是什么?

But how is this specified? How do you specify which Property that goes between the opening and closing tag in Xaml?
Is this set by some metadata in the Dependency Property or what?

谢谢

推荐答案

有一个应用于类的 ContentPropertyAttribute.WPF/Silverlight 将使用反射来确定要使用的属性.

There is a ContentPropertyAttribute that is applied to a class. WPF/Silverlight will use reflection to determine which property to use.

如果你想用自定义类来做到这一点,你可以这样做:

If you want to do this with a custom class, you can do it like so:

[ContentProperty("Bar")]
public class Foo : Control
{
    public static DependencyProperty BarProperty = DependencyProperty.Register(
        "Bar",
        typeof(int),
        typeof(Foo),
        new FrameworkPropertyMetaData(0));

    public int Bar
    {
        get { return (int)GetValue(BarProperty); }
        set { SetValue(BarProperty, value); }
    }
}

然后您可以像这样在 XAML 中指定它:

Then you could specify it in XAML like so:

<lcl:Foo>12</lcl:Foo>

更新

因为它使用反射,所以你真的不需要做一个 DependencyProperty.例如,这也可以:

Since it is using reflection, you don't really need to do a DependencyProperty. For instance, this will also work:

[ContentProperty("Bar")]
public class Foo : Control
{
    public int Bar { get; set; }
}   

这篇关于指定 Xaml 中的开始和结束标记之间的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆