单击按钮时更改标签内容

时间:2016-02-05 10:01:42

标签: c# wpf xaml

我希望StackPanel带有动态添加的按钮,用于在点击时更新标签内容。我使用Button.Click="ChildsButtonClick"将事件从StackPanel分配给它的子项并更新标签内容。但是,是否可以仅使用XAMLBindingsTriggers等进行此操作?正如你认为我是这个世界的新手。

XAML:

<StackPanel HorizontalAlignment="Left"
                Height="165"
                VerticalAlignment="Top"
                Width="465"
                Button.Click="ChildsButtonClick">
        <Button x:Name="button"
                Content="Button1"
                d:LayoutOverrides="Height" />
        <Button x:Name="button1"
                Content="Button2"
                d:LayoutOverrides="Height" />
    </StackPanel>
    <Label x:Name="label"
           Content="Label"
           HorizontalAlignment="Left"
           Margin="0,195,0,0"
           VerticalAlignment="Top" />

CS:

private void ChildsButtonClick(Object sender, RoutedEventArgs e)
    {
        Button a = e.Source as Button;
        if (a != null)
        {
            label.Content = a.Content;
        }
    }

如果没有事件,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

我让这个工作。在后面的代码中不使用任何事件。不确定它是否会对你有所帮助,但你可能能够适应它。

<Grid>
   <Grid.Triggers>
        <EventTrigger RoutedEvent="Button.Click" SourceName="Button">
              <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="label" Storyboard.TargetProperty="Content">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="Content"/>
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
              </EventTrigger.Actions>
        </EventTrigger>
  </Grid.Triggers>
        <DockPanel>
        <Label DockPanel.Dock="Top" x:Name="label">Hi</Label>
        <Button x:Name="Button" DockPanel.Dock="Bottom" Height="50" Width="50">

        </Button>
        </DockPanel>
    </Grid>