通过单击按钮访问画布名称

本文关键字:布名 访问 按钮 单击 | 更新日期: 2023-09-27 18:16:55

我的窗口有50多个按钮,每个按钮都有一个画布。

button1 for example:

                <Button x:Name="button1" HorizontalAlignment="Left" Margin="98,292,0,0" VerticalAlignment="Top" Width="85" Height="115" FontSize="25" Background="Red" BorderBrush="White" Foreground="White" Click="button1_Click" MouseDown="button1_MouseDown">
                    <StackPanel>
                        <TextBlock TextAlignment="Center" RenderTransformOrigin="-0.643,1.424" HorizontalAlignment="Center" VerticalAlignment="Center"><Run Text="1"/></TextBlock>
                        <Canvas x:Name="canvas1"/>
                    </StackPanel>
                </Button>

我的问题是,如何在button1_Click事件中获取画布的名称?我想做一个函数,所以我可以触发不同的画布'。例如:

void clearCanvas(int canvasNumber)
{
    canvas(+canvasNumber).Clear();
}

通过单击按钮访问画布名称

我想你需要这样的东西:

private void button1_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    Canvas canvas = ((StackPanel)btn.Content).Children
                                             .OfType<Canvas>()
                                             .First();
    canvas.Children.Clear();
    //at this point you can also get corresponding `Canvas` name 
    //(if you really have to) :
    //String name = canvas.Name;
}