2011-01-07 52 views
11

打開和關閉標籤之間請看下面的XAML指定哪些屬性去在XAML

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

這將設置TextBox (僅限WPF)

    • Text屬性內容屬性按鈕
    • 網格的兒童屬性

    但是這是如何指定的?您如何指定Xaml中的開始和結束標記之間的哪個屬性?
    這是由依賴屬性中的某些元數據設置的還是什麼?

    由於

  • +1

    這是一個很好的問題,我也想知道這一點。 – VoodooChild 2011-01-07 21:01:37

    +0

    只是事實上你不能用`TextBox`來做這件事。 – AnthonyWJones 2011-01-08 16:13:18

    回答

    17

    有被施加到一類ContentPropertyAttribute。 WPF/Silverlight將使用反射來確定使用哪個屬性。

    如果你想用一個自定義類來做到這一點,你可以像這樣:

    [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指定它,像這樣:

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

    更新

    由於它使用的是反射,你並不需要做一個DependencyProperty。例如,這也將工作:

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