以编程方式更改WPF中的按钮图标
我目前有一个按钮,上面有一个图标/图像。 我在XAML中配置了按钮和图像:
我需要能够以编程方式将此按钮的图像从playIcon更改为stopIcon。 我怎样才能做到这一点?
您可以通过事件处理程序更改按钮的内容来完成此操作。
你可以在Window.Resources
下设置“Play”图标和“Stop”图标作为资源,如下Window.Resources
:
现在,当单击按钮时,您只需将按钮的内容更改为其他资源(停止图标)。 在按钮的事件处理程序中,您可以执行以下操作:
C#
private void Button_Click(object sender, RoutedEventArgs e) { if (MediaButton.Content == FindResource("Play")) { MediaButton.Content = FindResource("Stop"); } else { MediaButton.Content = FindResource("Play"); } }
编辑:缩短表示法
MediaButton.Content = FindResource(MediaButton.Content == FindResource("Play") ? "Stop" : "Play");
希望这有帮助,如果您有任何其他问题,请告诉我。
如果您的图像定义如下:
然后在您想要进行切换的代码中,只需:
ImageSource = image;
其中image
定义为:
image = new BitmapImage(new Uri("/Application;component/Resources/pause.png", UriKind.Relative));
当然,它依赖于您使用MVVM模式并在代码中实现INotifyPropertyChanged
接口。
在更改条件上使用图像样式(/编辑)中的DataTrigger (编辑) :
然后, myCondition
变量将成为ViewModel中的布尔属性(或者更常见的是Control的DataContext),类似于
public bool myCondition { get { return ([whatever that condition might be]); } }
这也可能包括一个setter,也可能是一个简单的自动属性。 与其他MVVM答案一样,它将依赖ViewModel来实现INotifyPropertyChanged
。
好处是,一旦条件不再满足,DataTrigger将自动将Source属性设置回其原始值。
免责声明:我现在无法对此进行测试,因此请谨慎使用,并进行一些调试工作……
试试这个代码
window.Icon = BitmapFrame.Create(Application.GetResourceStream(new Uri("LiveJewel.png", UriKind.RelativeOrAbsolute)).Stream);