我们假设想创建一个左侧有一个小椭圆的自定义按钮。 我想这个椭圆的颜色是数据可绑定的。如何在自定义模板中使用自定义属性?
所以我启动了Blend并在表面上放了一个按钮,并且Edit a Copy of the Template
。 现在我有我的自定义模板,我把一个小的小Ellipse
里面:
...
<Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="3">
<Grid Background="{TemplateBinding Background}" Margin="1">
<snip />
<!-- My ellipse here -->
<Ellipse x:Name="ellipse" Width="10" Height="10" HorizontalAlignment="Left" />
</Grid>
</Border>
...
我右键点击这个按钮并选择Make into UserControl
命名MyButton
。 在后面的代码为这个按钮我添加自定义dependency property for the
Brush`:
public Brush MyColor
{
get { return (Brush)GetValue(MyColorProperty); }
set { SetValue(MyColorProperty, value); }
}
public static readonly DependencyProperty MyColorProperty = DependencyProperty.Register("MyColor", typeof(Brush), typeof(MyButton), new PropertyMetadata(new opertyChangedCallback(MyColorPropertyChanged)));
private static void MyColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var thisControl = d as MyButton;
}
然后我就可以用我的自定义按钮:
<local:MyButton Width="130" MyColor="Red"/>
但后来我卡。如何将我的Ellipse颜色(上面的x:Name =“ellipse”)绑定到我的MyColor
属性?
编辑:所以我绑定用户控件中的填充属性使用Fill={TemplateBinding MyColor}
,但后来我得到Property MyColor was not found in type Button
。 好的,所以我需要将我的模板定位到自定义MyButton类型,但我该怎么做? 我可以简单地改变按钮myButton的,因为那时我得到Property 'ContentTemplate' was not found in type 'MyButton'
<UserControl
<snip/>
x:Class="SilverlightApplication1.MyButton">
<UserControl.Resources>
<Style x:Key="ButtonStyle1" TargetType="Button">
<snip/>
</Style>
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<Button Content="Test Button" Style="{StaticResource ButtonStyle1}"/>
</Grid>
</UserControl>
WPF? Asp.Net? ... – IAbstract
@IAbstract,XAML排除了ASP.NET,不是吗?我们剩下的就是WPF和/或Silverlight。我认为上下文是WPF/Silverlight不可知的,因此我的XAML标签。 –
重要的是要有完整的标签......有人可能正在寻找相同的解决方案,但使用WPF或Silverlight代替。我对Asp.Net并不熟悉 - 所以请原谅我的无知。我认为提供问题适用的所有标签很重要。 :) – IAbstract