How does WPF determine what property to set when setting the content of elements in XAML?

一个人想着一个人 提交于 2021-01-27 14:16:57

问题


I hope my title is clear....

What I mean is for exmaple when we define animation:

Xaml:

<StoryBoard>
    <DoubleAnimation..../>
</StoryBoard>

But if we defines same thing in code-behind, we could do:

DoubleAnimation myDAnimation = new DoubleAnimation();
.....
StoryBoard myStoryBoard = new StoryBoard();
myStoryBoard.Children.Add(myDAnimation);

I tried to look into StoryBoard's class definition, nothing special:

public sealed class Storyboard : Timeline
{
        public Storyboard();

        // Summary:
        //     Gets the collection of child System.Windows.Media.Animation.Timeline objects.
        //
        // Returns:
        //     The collection of child System.Windows.Media.Animation.Timeline objects.
        //     The default is an empty collection.
        public TimelineCollection Children { get; }
....
}

I know if I defines my own class with the above sytnax, in order to add into my Children, I would need to:

XAML:

<MyClass>
   <MyClass.Children>
      <MyClassCildrenItem..../>
   </MyClass.Children>
</MyClass>

So how did the Xaml knows the DoubleAnimation is should add into StoryBoard's Children property? If I need to do the same thing, what do I need to declare?


回答1:


There's an attribute for that: ContentPropertyAttribute

If you check the Syntax section of classes on MSDN you can see what properties will be set when specifying content. E.g. the ContentControl targets the Content property.




回答2:


TimelineGroup an ancestor of Storyboard has the Children property and it also has the ContentPropertyAttribute which specifies the Children property as the content property.



来源:https://stackoverflow.com/questions/9761574/how-does-wpf-determine-what-property-to-set-when-setting-the-content-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!