2012-08-06 72 views
0

我是WPF的新手,我想創建一個帶5個按鈕的WPF應用程序。點擊每個按鈕後,我想要在另一個面板上顯示內容。現在我只想讓不同的圖像顯示在右側面板上的按鈕點擊。創建多個面板並在按鈕上單擊顯示一個面板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; 
} 

我能得到的只有這麼遠。

回答

1

您可以設置Image控制的Source財產代碼:

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

你可以輕鬆地重複對所有按鈕相同的點擊處理程序,並檢查一個被按下其中:

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

如果你想從父面板中刪除一個子面板(或其他控件)並添加另一個子面板,則必須修改面板的Children屬性:

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

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

如果你想動態地創建子面板,這種方法通常是有意義的。如果您想在XAML中聲明所有內容,則可以將所有子面板放入網格中,並像以前一樣更改其可見性。

但是,您也可能更改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); 
} 

或完全忽略按鈕/表格/面板設計,並使用TabControl

+0

在每個按鈕的點擊上,我想要在面板上顯示不同的圖像。我該如何設置圖像出現在StackPanel中,以及將來我會在StackPanel的Button按鈕上顯示不同的面板。請給出一些建議 – Shee 2012-08-06 12:03:17

+0

您的XAML顯示您有5個不同的Click處理程序,因此您可以設置5個不同的圖像。不是最有效的方法。我會編輯我的答案,給你一個提示如何繼續。 – Clemens 2012-08-06 12:06:15

+0

我明白了,謝謝。還可以給我一個關於如何覆蓋面板並只顯示一個並隱藏其餘按鈕的提示。假設我想要顯示一個包含很多內容的面板,而不是一個圖像,那我該怎麼做? – Shee 2012-08-06 12:14:09