繁体   English   中英

在wpf中创建多个面板并在按钮上显示一个面板

[英]creating multiple panels and displaying one panel on button click in wpf

我是WPF的新手,我想用5个按钮创建WPF应用程序。 在单击每个按钮时,我希望将内容显示在另一个面板上。 现在,我只希望单击按钮时在右侧面板上显示不同的图像。

这是我的XAML代码:

<Window x:Class="GridButton.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MyFirstApp" Height="350" Width="525" Loaded="Window_Loaded">
<Viewbox Stretch="Fill" StretchDirection="Both">
<DockPanel>
    <StackPanel DockPanel.Dock="left" Margin="5" Width="Auto" VerticalAlignment="Center" Height="Auto">
        <Button  Content="1" Name="button2" Click="button2_Click">
       </Button>
        <Button Content="2" Name="button1" Click="button1_Click_1">
</Button>
        <Button Content="3" Name="button3"  Click="button3_Click">
          </Button>
        <Button Content="4" Name="button4" Margin="5">
          </Button>
        <Button Content="5" Name="button5" Margin="5" Click="button5_Click_1">
          </Button>
    </StackPanel>
        <StackPanel DockPanel.Dock="Right">
            <Image Name="img1" Source="Blue Hills.jpg" Stretch="Uniform" Visibility="Hidden" ImageFailed="Image_ImageFailed" Height="257" />

        </StackPanel>

</DockPanel>

我的xaml.cs文件包含显示图像的代码:

private void button2_Click(object sender, RoutedEventArgs e)
{

    img1.Visibility = Visibility.Visible;
}

我只能做到这一点。

您可以在代码中设置Image控件的Source属性:

private void buttonx_Click(object sender, RoutedEventArgs e) 
{
    string path = ... // path to image file here
    img1.Source = new BitmapImage(new Uri(path));
}

您可以轻松地对所有按钮重复使用相同的Click处理程序,并检查按下了哪个按钮:

private void Button_Click(object sender, RoutedEventArgs e) 
{
    Button button = sender as Button;
    string path = null;
    if (button == button1)
    {
        path = ... // path to image file 1 here
    }
    else if ...

    if (path != null)
    {
        img1.Source = new BitmapImage(new Uri(path));
    }
}

如果要从父面板中删除子面板(或其他控件)并添加另一个面板,则必须修改面板的“ 儿童”属性:

<StackPanel Name="parent">   
    <StackPanel Name="child" />   
</StackPanel>  

parent.Children.Remove(child);
parent.Children.Add(...); // some other control here

如果您想动态创建子面板,则这种方法通常很有意义。 如果要在XAML中声明所有内容,则可以将所有子面板放置在Grid中并像以前一样更改其可见性。

但是,您也可以更改ZIndex附加属性。

<Grid>
    <StackPanel Name="child1">
    </StackPanel>
    <StackPanel Name="child2">
    </StackPanel>
    <StackPanel Name="child3">
    </StackPanel>
</Grid>

默认情况下,child3是最高的,但是现在您可以将ZIndex设置为某个值> 0,以使另一个孩子最高。

private void Button_Click(object sender, RoutedEventArgs e) 
{
    ...
    // reset ZIndex on previous topmost panel to 0 before
    Panel.SetZIndex(child1, 1);
}

或完全省略Button / Grid / Panel设计并使用TabControl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM