我正在为WPF应用程序实现操纵杆。我想模拟点击按钮。我可以使用下面的代码运行事件,但我也想显示在UI中被单击的按钮。按钮和其他UI项可能吗?
var invokeProv = (IInvokeProvider) (new ButtonAutomationPeer(ButtonHome).GetPattern(PatternInterface.Invoke));
invokeProv?.Invoke();
ButtonHome.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
我最终将其作为可能的解决方案。在mainwindow类中,我放了...
public static readonly DependencyProperty ButtonPressedProperty =
DependencyProperty.Register("ButtonPressed", typeof(bool), typeof(MainWindow), new PropertyMetadata(null));
添加了一个属性...
private bool ButtonPressed
{
get => (bool) GetValue(ButtonPressedProperty);
set => SetValue(ButtonPressedProperty, value);
}
在主窗口xaml中,我放下按钮...
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=(windows:MainWindow.ButtonPressed)}" Value="True">
<Setter Property="Background" Value="{StaticResource PressedButtonBackground}"/>
<Setter Property="Foreground" Value="{StaticResource ButtonForeground}"/>
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=(windows:MainWindow.ButtonPressed)}" Value="False">
<Setter Property="Background" Value="{StaticResource ButtonBackground}"/>
<Setter Property="Foreground" Value="{StaticResource ButtonForeground}"/>
</DataTrigger>
</Style.Triggers>
</Style>
评估我刚刚使用过的操纵杆按钮ButtonPressed = gamepadButtons [3];
答案 0 :(得分:1)
我唯一想到的是,如果我在您的位置,我只需在xaml端创建数据触发器,如下所示:
<Button x:Name="btn" Height="30" Margin="0,5,0,0">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Green" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding ButtonPressed, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Value="True">
<Setter TargetName="bd" Property="Background" Value="Purple" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
然后我要创建一个属性:
private bool _buttonPressed;
public bool ButtonPressed
{
get
{
return _buttonPressed;
}
set
{
if (_buttonPressed != value)
{
_buttonPressed = value;
OnPropertyChanged(nameof(ButtonPressed));
}
}
}
在要引发该事件的地方,我只需更改布尔值状态
var invokeProv = (IInvokeProvider)(new ButtonAutomationPeer(ButtonHome).GetPattern(PatternInterface.Invoke));
invokeProv?.Invoke();
ButtonHome.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
ButtonPressed = true;
此解决方案中您需要记住的事情:
实现INotifyPropertyChanged接口,
确保您的按钮模板可以到达创建我们属性的数据上下文,例如,我将RelativeSource设置为Window祖先类型,我认为这并不是真正必要的。您可能会做得更好,更快。
如果有更好的解决方案来提高UI元素的可视状态,我想了解一下!亲切的问候。