一部のボタンにアイコンを表示したい。ボタン内に画像を配置するのは簡単ではないので、ユーザー コントロール、派生コントロール、または何かが役立つと思います。そこで、ググって、試して、コンパイルして、次のコードを思いつきました。
残念ながら、私のプロパティは何にもバインドされておらず、テキストも画像も表示されません。どうすればこれを機能させることができますか?欠けているピースは何ですか?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();
}
}