gpt4 book ai didi

wpf - 使用触发器更改 xaml 中的图像源无法正常工作

转载 作者:行者123 更新时间:2023-12-04 15:26:48 25 4
gpt4 key购买 nike

我需要根据 viewModel 中的一些 bool 属性更改工具栏中的图像。我正在使用触发器来更改图像源。这是正确的方法吗?我的代码运行不正常,有时它可以工作,但有时图像保持不变。

<Image x:Key="startPauseResumeAnalysisToolbarImage" >
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="Resources/ToolbarIcons/play.png" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsAnalysisRunning}" Value="True" >
<Setter Property="Source" Value="Resources/ToolbarIcons/pause.png"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>

最佳答案

它应该工作。很难理解为什么它没有其余的代码。您是否在具有 IsAnalysisRunning 属性的任何类中实现 INotifyPropertyChanged 接口(interface)?

这是我用来测试的一个小样本:

主窗口.xaml

<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Image >
<Image.Style>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="Desert.jpg" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsAnalysisRunning}" Value="True" >
<Setter Property="Source" Value="Koala.jpg"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
</Window>

MainWindow.xaml.cs:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
private bool _isAnalysisRunning = false;
public bool IsAnalysisRunning
{
get { return _isAnalysisRunning; }
set {
_isAnalysisRunning = value;
NotifyPropretyChanged("IsAnalysisRunning");
}
}
private void NotifyPropretyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}


public event PropertyChangedEventHandler PropertyChanged;

private void button1_Click(object sender, RoutedEventArgs e)
{
IsAnalysisRunning = !IsAnalysisRunning;
}
}

关于wpf - 使用触发器更改 xaml 中的图像源无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5660608/

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