【发布时间】:2011-10-14 15:14:19
【问题描述】:
假设要创建一个左侧有一个小椭圆的自定义按钮。 我希望这个椭圆的颜色是数据可绑定的。
所以我启动了 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>
...
我右键单击此按钮并选择名为MyButton 的Make into UserControl。
在此按钮后面的代码中,我添加了一个自定义 dependency property for theBrush`:
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} 绑定用户控件中的 Fill 属性,但随后我得到 Property MyColor was not found in type Button。
好的,所以我需要将我的模板定位到自定义 MyButton 类型,但我该怎么做呢?
我可以简单地将 Button 更改为 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>
【问题讨论】:
-
@IAbstract,XAML 确实排除了 ASP.NET,不是吗?我们剩下的是 WPF 和/或 Silverlight。我认为上下文与 WPF/Silverlight 无关,因此是我的 XAML 标记。
-
拥有完整的标签很重要......有人可能正在寻找相同的解决方案,但改用 WPF 或 Silverlight。我对 Asp.Net 还不是很熟悉——所以请原谅我的无知。我确实认为提供问题适用的所有标签很重要。 :)
标签: c# silverlight xaml wpf-controls