WPF 鼠标悬停在StackPanel上时,出现两个按钮,StackPanel里面有一个照片,两个按钮,两个按钮都居中,并且能够点击触发View Model端命令,使用触发器 实现此效果
时间: 2024-02-06 13:11:45 浏览: 138
设置wpf中Button的划过样式的分析
3星 · 编辑精心推荐
可以使用WPF中的触发器(Trigger)来实现此效果。以下是实现的步骤:
1. 在StackPanel中添加一个Image和两个Button,并设置它们的Visibility属性为Collapsed,同时设置HorizontalAlignment和VerticalAlignment为Center,使它们居中。
2. 在StackPanel上添加一个触发器(Trigger),当鼠标进入StackPanel时,将Image和两个Button的Visibility属性设置为Visible,使它们出现。
3. 在StackPanel上添加另一个触发器(Trigger),当鼠标离开StackPanel时,将Image和两个Button的Visibility属性设置为Collapsed,使它们消失。
4. 在View Model中添加两个命令,分别用于处理两个按钮的点击事件。
5. 将两个按钮的Command属性绑定到View Model中的命令,使它们能够触发命令。
以下是XAML代码示例:
```xml
<StackPanel Background="LightGray" Width="200" Height="200">
<Image Source="path/to/image.png"/>
<Button Content="Button 1" Visibility="Collapsed"
Command="{Binding Button1Command}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Content="Button 2" Visibility="Collapsed"
Command="{Binding Button2Command}"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
<StackPanel.Triggers>
<EventTrigger RoutedEvent="StackPanel.MouseEnter">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility"
Duration="0:0:0"
BeginTime="0:0:0">
<DiscreteObjectKeyFrame KeyTime="0:0:0"
Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="StackPanel.MouseLeave">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Visibility"
Duration="0:0:0"
BeginTime="0:0:0">
<DiscreteObjectKeyFrame KeyTime="0:0:0"
Value="{x:Static Visibility.Collapsed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</StackPanel.Triggers>
</StackPanel>
```
在View Model中定义Button1Command和Button2Command命令,并在命令处理方法中添加逻辑代码。
```csharp
public ICommand Button1Command { get; set; }
public ICommand Button2Command { get; set; }
public MyViewModel()
{
Button1Command = new RelayCommand(ExecuteButton1Command);
Button2Command = new RelayCommand(ExecuteButton2Command);
}
private void ExecuteButton1Command()
{
// 处理按钮1点击事件的逻辑代码
}
private void ExecuteButton2Command()
{
// 处理按钮2点击事件的逻辑代码
}
```
其中,RelayCommand是一个常用的ICommand实现类,可以通过NuGet包管理器安装。
```csharp
public class RelayCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public RelayCommand(Action execute) : this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute?.Invoke() ?? true;
}
public void Execute(object parameter)
{
_execute();
}
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
```
阅读全文