1
我想在我的一些按鈕中顯示一個圖標。由於對齊按鈕內的圖像並不是很簡單,我通過用戶控件,派生控件或其他東西可以派上用場。所以我搜索了一下,嘗試了一下,編譯了一下,現在我想出了下面的代碼。帶有圖標的按鈕控件
不幸的是,我的屬性沒有綁定任何東西,我看不到文本和圖像。我該如何做這項工作?缺失的是什麼?我使用VS2010和.NET 4.0。
XAML:
<Button
x:Class="MyNS.IconButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Button.Template>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding IconSource}" Name="Icon" Width="{Binding IconSize}" Height="{Binding IconSize}" Margin="0,0,4,0"/>
<ContentPresenter/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsEnabled" Value="False">
<Setter Property="Image.Opacity" Value="0.5"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
代碼文件:
public partial class IconButton : Button
{
public static DependencyProperty IconSourceProperty = DependencyProperty.Register(
"IconSource",
typeof(ImageSource),
typeof(IconButton));
public static DependencyProperty IconSizeProperty = DependencyProperty.Register(
"IconSize",
typeof(int),
typeof(IconButton),
new PropertyMetadata(11));
public ImageSource IconSource
{
get { return (ImageSource) GetValue(IconSourceProperty); }
set { SetValue(IconSourceProperty, value); }
}
public int IconSize
{
get { return (int) GetValue(IconSizeProperty); }
set { SetValue(IconSizeProperty, value); }
}
public IconButton()
{
InitializeComponent();
}
}
有了這個,我看到這個圖標,但周圍沒有灰色邊框,也沒有文字。我想要一個帶有文本的普通灰色按鈕,但是除此之外還有一個_additional_圖標。 – ygoe 2012-08-07 07:11:58
好吧,我可以用這個添加文本:' ' - 但是仍然沒有背景和邊框以及錯誤的對齊。 –
ygoe
2012-08-07 07:18:10
無法像您嘗試那樣部分修改ControlTemplate - http://msdn.microsoft.com/zh-cn/library/aa970773.aspx。我看到你能夠做到這一點的兩種方式是在ContentPresenter周圍放置一個邊框,並自己完成所有的視覺效果,或者將它重新創建爲UserControl並讓UserControl傳遞按鈕的事件。 – Mitch 2012-08-08 12:47:53