Use AttachedProperty in Style in ControlTemplate
Here is my simple application:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style x:Key="Test">
<Setter Property="Button.Template">
<Setter.Value>
<ControlTemplate>
<Border BorderBrush="Blue"
BorderThickness="3"开发者_如何转开发
Background="Black"
CornerRadius="{Binding app:Extras.CornerRadius}"
>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Height="23"
HorizontalAlignment="Left"
Margin="29,26,0,0"
Name="button1"
VerticalAlignment="Top" Width="75"
app:Extras.CornerRadius="10"
Style="{StaticResource Test}"
>Button</Button>
</Grid>
</Window>
Here is my AttachedProperty:
namespace WpfApplication1
{
public class Extras
{
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.RegisterAttached(
"CornerRadius",
typeof(double),
typeof(Button),
new FrameworkPropertyMetadata(1.0d, FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetCornerRadius(UIElement element, double value)
{
element.SetValue(CornerRadiusProperty, value);
}
public static double GetCornerRadius(UIElement element)
{
return (double)element.GetValue(CornerRadiusProperty);
}
}
}
CornerRadius="{Binding app:Extras.CornerRadius}"
this of course doesn't work. so how can I get value from here app:Extras.CornerRadius="10"
thanks in advance!
Use a TemplateBinding
rather than a Binding
:
<Border BorderBrush="Blue"
BorderThickness="3"
Background="Black"
CornerRadius="{TemplateBinding app:Extras.CornerRadius}"
>
OK, try that then :
<Border BorderBrush="Blue"
BorderThickness="3"
Background="Black"
CornerRadius="{Binding (app:Extras.CornerRadius), RelativeSource={x:Static RelativeSource.TemplatedParent}}"
>
精彩评论