在 WPF 中,每个控件都有其默认模板(外观),但你可以轻松地更改这些模板并使控件看起来符合你的要求。这使得按照功能选择控件并使其外观符合你的要求变得更加容易。在你的情况下,你想要 Click
,所以你选择 Button
并更改其 Template
<Window ...>
<Window.Resources>
<Style TargetType="{x:Type Button}" x:Key="ImageButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<ContentPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Button Style="{StaticResource ImageButtonStyle}" Click="ImageButton_Click">
<Image Source="..."/>
</Button>
</Window>
通过上述XAML,Image
将成为您的Button
编辑
在下面,您可以找到如何绑定/更改Image.Source
的简化版本,其中所有内容都在MainWindow中完成,但基本上在WPF中,您不会操纵控件,而是使用Binding
绑定它们的属性并操作这些属性。通常,您需要创建专用类(ViewModel)。您的类需要实现INofityPropertyChanged
接口,DataContext
需要相应地设置,并且绑定的属性需要在每次更改其值时触发INofityPropertyChanged.PropertyChanged
事件(这样才能通知UI刷新值)。
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private ImageSource _myImageSource;
public ImageSource MyImageSource
{
get { return _myImageSource; }
set
{
_myImageSource = value;
OnPropertyChanged("MyImageSource");
}
}
private void ImageButton_Click(object sender, RoutedEventArgs e)
{
this.MyImageSource = new BitmapImage(...);
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
并且在 XAML 中:
<Button Style="{StaticResource ImageButtonStyle}" Click="ImageButton_Click" Width="..." Height="...">
<Image Source="{Binding MyImageSource}"/>
</Button>