Reputation: 41
I want to implement a knob in resource dictionary that could receive an image as template. When I implemented it in the same library, it worked well :
knob.xaml :
<UserControl x:Class="SwitchesLibrary.Knob"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="96" Width="96" x:Name="This">
<Grid>
<Image RenderTransformOrigin=".5,.5" Source="Images/Knobs/Knob.png" Height="96" Width="96" >
<Image.RenderTransform>
<RotateTransform Angle="{Binding Angle, ElementName=This}"/>
</Image.RenderTransform>
</Image>
</Grid>
knob.cs
public static readonly DependencyProperty AngleProperty =
DependencyProperty.Register("Angle",
typeof(double),
typeof(ExampleKnobLocklessAnalogLarge),
new FrameworkPropertyMetadata(0.0,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
null,
coerceValueCallback));
public double Angle
{
get { return (double)GetValue(AngleProperty); }
set { SetValue(AngleProperty, value); }
}
but when I moved it to resource dictionary :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SwitchesLibrary">
<Style TargetType="local:Knob">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Knob">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Image
x:Name="image"
Source="{TemplateBinding KnobImage}"
RenderTransformOrigin=".5,.5"
Stretch="Fill"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
<Image.RenderTransform>
<RotateTransform Angle="{TemplateBinding Angle}"/>
</Image.RenderTransform>
</Image>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
It's seem to work well (the angle value is updated correctly), but the knob image is not rotating. Why ?
Upvotes: 0
Views: 205
Reputation: 169420
Try to replace the TemplateBinding
with a RelativeSource
binding;
<RotateTransform Angle="{Binding Angle, RelativeSource={RelativeSource AncestorType=local:Know}, Mode=OneWay}"/>
{TemplateBinding}
is an optimized version of a binding that doesn't work very well in all scenarios.
Upvotes: 3