2011-04-14 50 views
6

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

<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> 
+0

我也有这个问题,它不” t似乎翻转。 – tofutim 2015-10-13 20:53:58

回答

4

它应该工作。很难看出它为什么没有代码的其余部分。你在任何具有IsAnalysisRunning属性的类中实现INotifyPropertyChanged接口吗?

这里是一个小样品I用于测试此:

MainWindow.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; 
    } 
} 
+0

非常感谢,你让我的一天! – 2017-04-20 17:05:31