2015-08-14 46 views
2

有一個StackPanel一個按鈕buttonPlay內部,將其豐富的內容,如圖像和標籤WPF

<Button Height="37" HorizontalAlignment="Left" Margin="222,72,0,0" Name="buttonPlay" Click="buttonPlay_Click"> 
    <StackPanel Orientation="Horizontal"> 
    <Image Source="play.jpg" Height="20" Width="27" /> 
    <Label Padding="4" Height="27" Width="55" FontWeight="Bold" FontFamily="Times New Roman"> Play</Label> 
    </StackPanel> 
</Button> 

我想在標籤和圖像中的文本改變,當我點擊按鈕,這樣做buttonPlay_Click事件我有,如果還有條件,但我不知道如何更改標籤或圖像。

private void buttonPlay_Click(object sender, RoutedEventArgs e) 
{ 
    if (buttonPlay.Content.ToString() == "Play") 
    { 
     //....some actions 
     buttonPlay.Content = "Stop"; 
    } 
    else 
    { 
     //.....some other actions 
     buttonPlay.Content = "Play"; 
    } 
} 

如何根據點擊更新標籤和圖像?

回答

2

給你的Label和你的Image一個名字。就像這樣:

<StackPanel Orientation="Horizontal" Name="hh"> 
    <Image Height="20" Width="27" Name="img" Source="play.jpg" /> 
    <Label Padding="4" Height="27" Width="55" Name="lbl" FontWeight="Bold" FontFamily="Times New Roman">Play</Label> 
</StackPanel> 

private void buttonPlay_Click(object sender, RoutedEventArgs e) 
{ 
    if (lbl.Content.ToString() == "Play") 
    { 
     //....some actions 
     lbl.Content = "Stop"; 
     BitmapImage btm = new BitmapImage(); 
     btm.BeginInit(); 
     btm.UriSource = new Uri("pack://application:,,,/WpfApplication1;component/Resources/stop.png"); 
     btm.EndInit(); 
     img.Source = btm; 
    } 
    else 
    { 
     //.....some other actions 
     lbl.Content = "Play"; 
    } 
} 
+0

但是如何處理與圖像更新? – cMinor

+0

你是否希望圖像和標籤在條件更新? –

+0

是他們兩個都要更新 – cMinor

3

最簡單的方法是爲子控件設置名稱,例如buttonPlayImagebuttonPlayLabel,然後您可以使用.運算符訪問它們的屬性。

private void buttonPlay_Click(object sender, RoutedEventArgs e) 
{ 
    if (buttonPlayLabel.Content == "Play") 
    { 
     buttonPlayLabel.Content = "Stop"; 

     buttonPlayImage.Source = new BitmapImage(new Uri("stop.png")); 
    } 
    else 
    { 
     //other actions 
    } 
} 

而對於名稱:

<Image Name="buttonPlayImage" ... /> 
<Label Name="buttonPlayLabel" ... >Play</Label> 
+0

我想'buttonPlayImage.Source = 「stop.png」'但是我得到'錯誤不能鍵入 '串' 隱式轉換爲「System.Windows.Media.ImageSource'' – cMinor

+0

用新代碼嘗試一下。 –

+0

我想我錯過了一些我得到錯誤'System.Windows.Media.Imaging.BitmapImage.BitmapImage(System.Uri)'的最佳重載方法匹配'有一些無效參數' – cMinor

0

你應該到圖像和標籤提供姓名,然後更新這兩個來源和內容。你不應該更新按鈕內容,因爲它將取代所有的StackPanel,結果Image和Label都消失。