Wpf ToggleButton命令绑定数据触发器

时间:2014-03-07 19:06:48

标签: wpf data-binding datatrigger

我有一个切换按钮,它有两个绑定到按钮IsChecked属性的数据触发器。在Data触发器中,我设置了按钮内容以及它的命令属性。我遇到的问题是,当您单击按钮时,数据触发器正在更改命令值,然后触发命令。是否可以首先触发命令然后触发数据?这是代码。

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

我想要发生的是,当第一次触发Build命令时单击该按钮,然后第二次单击该按钮以取消CancelBuild命令。

1 个答案:

答案 0 :(得分:4)

保持简单:

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

视图模型:

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();
    }
}