WPFでオン/オフボタンを作成したいのですが、ユーザーがクリックしたときに外観を変更したいです(オンの場合はオフに、オフの場合はオンに切り替えます)。使用したい画像をリソースに追加しました。
<Window.Resources>
<Image x:Key="Off1" Source="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
<Image x:Key="On1" Source="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>
</Window.Resources>
イベントコードは、「フラグ」は真として初期化されるブールローカル変数です。
private void OnOff1Btn_Click(object sender, RoutedEventArgs e)
{
if (flag)
{
OnOff1Btn.Content = FindResource("Off1");
flag = false;
}
else
{
OnOff1Btn.Content = FindResource("On1");
flag = true;
}
}
ここで、同じように動作する 2 つのオン/オフ ボタンを作成する必要があります。2 番目のボタンに同じリソースを使用しようとすると、例外が発生しました。
Specified element is already the logical child of another element. Disconnect it first.
2 番目のボタンで同じ画像リソースを使用できますか? それとも、別のキーを持つリソースとして画像を再度追加する必要がありますか?