我們假設想創建一個左側有一個小橢圓的自定義按鈕。 我想這個橢圓的顏色是數據可綁定的。如何在自定義模板中使用自定義屬性?
所以我啓動了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