[英]Click Event for WPF Image
我正在將舊的 WinForms 桌面應用程序移植到 WPF。 應用程序 GUI 使用 WinForm 的PictureBox
來顯示圖像。 舊的 WinForms 應用程序還具有用於所有圖片框的OnClick
事件處理程序。 單擊圖像實際上做了一些重要的事情。 現在,我重新做在WPF用戶界面,我發現按照這個的等效的WinForm的PictureBox
控件是WPF的Image
。 但是,當我打開 WPF Image
的屬性面板時,沒有要處理的click
事件,因此我無法像在 WinForms 中那樣編寫單擊事件處理程序。
那么,你能告訴我可以做些什么來實現 WinForm 的PictureBox
和它在 WPF 中的點擊事件嗎? 我想在每次用戶單擊圖像時顯示圖像並處理案例。
只需像這樣向您的圖像添加一個 MouseDown(或建議的 MouseLeftButtonDown)事件
<Image x:Name=aPicture Source="mypic.jpg" MouseDown="aPicture_MouseDown"/>
// or
<Image x:Name=aPicture Source="mypic.jpg" MouseLeftButtonDown="aPicture_MouseDown"/>
這應該將它添加到您的代碼后面
private void aPicture_MouseDown(object sender, MouseEventArgs e)
{
//do something here
}
在 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(...); //you change source of the Image
}
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>
為了獲得完整的可點擊體驗,我建議使用 CJK 方法並將 Cursor 屬性設置為 Hand。
<Image x:Name="btnSearch" Source="/Images/search/search.png" MouseDown="btnSearch_MouseDown" Cursor="Hand"/>
也許MouseLeftButtonDown會更合適。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.