Question

I have a toggle button that has two data triggers that are bound to the buttons IsChecked property. Within the Data triggers I am setting the buttons content and also its command property. The problem that I am having is that when you click the button the data trigger is changing the command value and then firing the command. Is it possible to have the command fire first then the data trigger? Here is the code.

 <ToggleButton x:Name="commandToggleButton" Grid.Row="0"  Height="30" HorizontalAlignment="Left" Margin="26,24,0,0"  VerticalAlignment="Top" Width="75">
                <ToggleButton.Style>
                    <Style TargetType="ToggleButton">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=commandToggleButton, Path=IsChecked}" Value="False">
                                <Setter Property="Content" Value="Build" />
                                <Setter Property="FontWeight" Value="Bold" />
                                <Setter Property="Command" Value="{Binding Build}" />
                            </DataTrigger>
                            <DataTrigger Binding="{Binding ElementName=commandToggleButton, Path=IsChecked}" Value="True">
                                <Setter Property="Content" Value="Cancel" />
                                <Setter Property="FontWeight" Value="Bold" />
                                <Setter Property="Command" Value="{Binding CancelBuild}" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ToggleButton.Style>
            </ToggleButton>

What I would like to happen is that when the button is clicked the first time for the Build command to be fired, then if it is clicked the second time for the CancelBuild command to be fired.

Was it helpful?

Solution

Keep it simple:

<ToggleButton IsChecked="{Binding EnableBuild}" FontWeight="Bold">
   <ToggleButton.Style>
        <Style TargetType="ToggleButton">
            <Style.Triggers>
               <Trigger Property="IsChecked" Value="False">
                   <Setter Property="Content" Value="Build" />
               </Trigger>

               <Trigger Property="IsChecked" Value="True">
                  <Setter Property="Content" Value="Cancel" />
               </Trigger>
            </Style.Triggers>
         </Style>
   </ToggleButton.Style>
</ToggleButton>

ViewModel:

public Command Build {get;set;}
public Command Cancel {get;set;}

//...

private bool _enableBuild;
public bool EnableBuild
{
    get { return _enableBuild; }
    set
    {
       _enableBuild = value;
       NotifyPropertyChange(() => EnableBuild);

       if (value)
          Build.Execute();
       else
          Cancel.Execute();
    }
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top