gpt4 book ai didi

WPF 单击时更改按钮背景图像

转载 作者:行者123 更新时间:2023-12-04 03:21:57 25 4
gpt4 key购买 nike

我创建了一个 Button并设置其背景Image .我想要的是当Button被点击,我要更换背景Image与另一个

我怎样才能做到这一点?

这是我的代码 Button :

<Button x:Name="PopulationReporting" Click="PopulationReporting_Clicked" Width="172" 
Height="60" Margin="57,170,57,184">
<Button.Background >
<ImageBrush ImageSource="images/img-2.png" />
</Button.Background>
</Button>

最佳答案

您可以通过编程方式执行此操作(参见示例 here )

或者

您可以使用 DataTriggers ,其中 DataTrigger绑定(bind)到 bool ViewModel 中的值(value)并更改 Style您的Button . Button绑定(bind)到 Command ,所以在执行时,Command将改变 image 的状态(isPlaying 属性)。

xml:

<Button Height="23" HorizontalAlignment="Left" Margin="70,272,0,0" Name="buttonPlay" VerticalAlignment="Top" Width="75" Command="{Binding PlayCommand}" CommandParameter="{Binding ElementName=ButtonImage, Path=Source}" >
<Image Name="ButtonImage">
<Image.Style>
<Style TargetType="{x:Type Image}">
<Style.Triggers>
<DataTrigger Binding="{Binding isPlaying}" Value="True">
<Setter Property="Source" Value="Play.png" />
</DataTrigger>
<DataTrigger Binding="{Binding isPlaying}" Value="False">
<Setter Property="Source" Value="Stop.png" />
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</Button>

C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}

public class ViewModel : INotifyPropertyChanged
{
private bool _isPlaying = false;
private RelayCommand _playCommand;

public ViewModel()
{
isPlaying = false;
}

public bool isPlaying
{
get { return _isPlaying; }
set
{
_isPlaying = value;
OnPropertyChanged("isPlaying");
}
}

public ICommand PlayCommand
{
get
{
return _playCommand ?? new RelayCommand((x) =>
{
var buttonType = x.ToString();

if (null != buttonType)
{
if (buttonType.Contains("Play"))
{
isPlaying = false;
}
else if (buttonType.Contains("Stop"))
{
isPlaying = true;
}
}
});
}
}

public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class RelayCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;

public event EventHandler CanExecuteChanged;

public RelayCommand(Action<object> execute) : this(execute, null) { }

public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{

if (_canExecute == null)
{
return true;
}

return _canExecute(parameter);
}

public void Execute(object parameter)
{
_execute(parameter);
}

public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}

关于WPF 单击时更改按钮背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16319063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com