Subclassing FrameworkElement in Silverlight 4.0 - A Measure Pass Question
I currently have an issue in Silverlight where I开发者_开发百科 want to detect the change in size for an element, and react to it. However, listening with .SizeChanged
is actually not sufficient, as often I get a flash of the element at the size it's changing to, before the functionality in the .SizeChanged
is called. So I have perhaps a two-fold question.
My intention is to use the Measure pass to calculate the manipulations I want to apply before the size is visually changed, so that I can eliminate this flickering effect. As far as I'm aware, the only way to do this successfully is to create a UIElement that does these calculations on the Measure pass, before Measuring the rest of these elements.
As such, I was hoping to create a really light UIElement by extending off FrameworkElement. However, I can't get the stupid thing to display anything. I'm under the impression that at the FrameworkElement level, a subclass would require adding the content to the VisualTree and I can't seem to work out how to do that.
I was hoping to avoid extending off UserControl
, or Panel
, as they are far heavier than what I need, with so much extra functionality I dont want. I merely want to catch the Measure pass and perform some work there.
So, is it possible to extended off FrameworkElement
in Silverlight 4.0 and actually render something? If not, is it possible to listen for/interrupt the measure pass another way?
You cannot manually add content to the visual tree - this functionality is only exposed to built-in Silverlight controls.
In such a situation, you should derive from Control
and specify a default template for this control to use - in the default template, specify the desired contents of the visual tree.
To allow a default template to be used, you should specify DefaultStyleKey
in your contructor and give it the value of your control type. E.g. DefaultStyleKey = GetType()
.
Then, you can specify a style such as this, in e.g. Themes/Generic.xaml
<Style TargetType="my:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="my:MyControl">
<Rectangle Width="100" Height="100" Fill="Red" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Or if your control is a content-presenting control, just derive from ContentControl
and it takes care of all the plumbing - you just need to set Content
to whatever you wish to display and your subclass will only need to perform the measure-pass override logic.
精彩评论