2016-10-03 69 views
1

下面的兩種語法都適用。我的問題是WPF如何知道內容是我指定的?內容屬性如何工作

<Button> 
    <Button.Content> 
     my button 
    </Button.Content> 
</Button> 

<Button> 
    my button <!--how does wpf know this is the content--> 
</Button> 

同樣,如何WPF知道現在我加入ListBoxItems

<ListBox> 
    <!--ListBox.Items--> 
     <ListBoxItem Content="item 1" /> <!--XAML automatically knows I'm specifying items--> 
     item 2 
     <ListBoxItem Content="item 3" /> 
    <!--/ListBox.Items--> 
</ListBox> 

所以在ContentControl中,默認的屬性就是內容,並與ItemsControl的,默認的是項目,並與文本框,在默認是TextBox。
這個'默認'是如何工作的?
當我創建自定義控件時,如何創建此「默認屬性」?

回答

1

ContentPropertyAttribute告訴xaml解析器哪些屬性用於直接內容。

ContentControl,其中Button繼承,標記爲attibute [ContentProperty("Content")]。同樣,ItemsControlListBox的祖先)標記爲[ContentProperty("Items")]