只是嘗試了寫一個自定義的控制與this Stackoverflow question如何獲取從按鈕派生的CustomControl中的「默認按鈕外觀」?
的幫助,但Button控件上的按鈕除了圖像和文本空。
如果沒有其他指定,有沒有可能使用默認行爲?
我不想重新編寫一個完整的按鈕,如果已經存在一個幾乎適合的按鈕。只是想添加一個ImageSource和一個文本以及一些(而不是全部)樣式。
這是我得到的,也許我只是犯了一些錯誤。
類定義:
public class MyImageButton : Button
{
static MyImageButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyImageButton), new FrameworkPropertyMetadata(typeof(MyImageButton)));
}
public ImageSource ImageSource
{
get { return (ImageSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(MyImageButton), new UIPropertyMetadata(null));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyImageButton), new UIPropertyMetadata(null));
}
從generic.xaml
<Style TargetType="{x:Type local:MyImageButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyImageButton}">
<StackPanel Height="Auto" Orientation="Horizontal">
<Image Source="{TemplateBinding ImageSource}" Width="24" Height="24" Stretch="Fill" />
<TextBlock Text="{TemplateBinding Text}" HorizontalAlignment="Left" Foreground="Black" FontWeight="Bold" Margin="5,0,0,0" VerticalAlignment="Center" FontSize="12" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最後使用在主窗口XAML
<ctrl:MyImageButton ImageSource="SomeImage.png" Text="BlaBlubb" Height="100" Width="120" Click="CheckClick" />
'如果沒有其他指定,有沒有可能使用默認行爲?' - 我不明白。如果從'Button'繼承,則''''''''''''''已經具有'Button'的行爲。你的意思是外表?這些是WPF中2個完全不同的(和獨立的)概念。 – 2013-03-14 15:28:32
我想要的是一個按鈕,而不是圖像和文本。這似乎在這裏被摧毀。我在主窗口中獲取了兩個元素,但沒有任何東西看起來接近按鈕 – 2013-03-14 15:30:22
這是因爲您的ControlTemplate只是指定您正在看到的內容 - 具有圖像和TextBlock的StackPanel。一個按鈕的ControlTemplate實際上要複雜得多。請參閱[本頁](http://dotnet.dzone.com/news/wpf-kid-stuff-extracting)瞭解如何提取按鈕的ControlTemplate或[此MSDN示例](http:// msdn .microsoft.com/en-us/library/ms753328%28v = vs.85%29.aspx)Button ControlTemplate。 – 2013-03-14 15:41:57