如何在Xaml中单击时更改按钮内容?

时间:2013-07-09 05:05:56

标签: c# xaml

我有一个名为Hold按钮的buttoncontent。一旦我点击按钮按钮内容应该更改为恢复,再次按下恢复按钮意味着保持应该是可见的。

XAML代码:

 <Button Style="{StaticResource CommonButtonStyle}" Template="{DynamicResource GlassButton}" ToolTip="F9" Click="Hold_Click" PreviewKeyDown="Hold_PreviewKeyDown" Name="OK" Margin="1,49,25,0" Grid.Column="2" Grid.Row="13" Grid.RowSpan="2">
        <StackPanel Style="{StaticResource ButtonStackPanel}">
            <Image Style="{StaticResource CancelImages}" />
            <TextBlock Text="{Loc lblHold}" Style="{StaticResource ButtonTextBlock}" />
        </StackPanel>
  </Button>

3 个答案:

答案 0 :(得分:8)

你可以在按钮的Click事件中尝试这样的事情:

private void holdResumeButton_Click(object sender, RoutedEventArgs e)
{
        if ((string)holdResumeButton.Content == "Hold")
            holdResumeButton.Content = "Resume";

        else
            holdResumeButton.Content = "Hold";

}

XAML:

<Button x:Name="holdResumeButton" 
        Content="Hold"
        Click="holdResumeButton_Click"/>

答案 1 :(得分:4)

使用ToggleButton

        <Style x:Key="HoldOrResumeButton" TargetType="{x:Type ToggleButton}" BasedOn="{StaticResource {x:Type ToggleButton}}">
            <Setter Property="Content">
                <Setter.Value>
                    <TextBlock Text="Hold"/>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsChecked, RelativeSource={RelativeSource Mode=Self}}" Value="True">
                    <Setter Property="Content">
                        <Setter.Value>
                            <TextBlock Text="Resume"/>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>

答案 2 :(得分:1)

也许您可以使用ToggleButton代替Button,以便绑定到IsChecked属性。 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.togglebutton.ischecked.aspx

例如:

    <ToggleButton x:Name="TB">
        <ToggleButton.Style>
            <Style>
                <Style.Triggers>
                    <Trigger Property="ToggleButton.IsChecked" Value="True">
                        <Setter Property="ToggleButton.Content" Value="Resume"></Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ToggleButton.Style>
    </ToggleButton>