11

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 番目のボタンで同じ画像リソースを使用できますか? それとも、別のキーを持つリソースとして画像を再度追加する必要がありますか?

4

3 に答える 3

16

スタイルで Shared を false に設定します

<StackPanel >
   <StackPanel.Resources>
      <Image x:Key="flag" Source="flag-italy-icon.png" Width="10" x:Shared="false"/>
   </StackPanel.Resources>

   <ContentControl Content="{DynamicResource flag}" />
   <ContentControl Content="{DynamicResource flag}" />

于 2013-10-11T06:37:56.840 に答える
12

画像共有にはBitmapImageを使用する必要があります。

<BitmapImage x:Key="Off1" UriSource="/WPFApplication;component/Images/off_button.png" Height="30" Width="70" />
<BitmapImage x:Key="On1" UriSource="/WPFApplication;component/Images/on_button.png" Height="30" Width="70"/>

その後、BitmapImage で複数の画像を作成できます

XAML で

 <Button ..>
  <Button.Content>
   <Image Source="{StaticResource Off1}" />
  </Button.Content>
 </Button>

コード内

  Image image = new Image();
  image.Source = FindResource("Off1");
  OnOff1Btn.Content = image; 
于 2013-01-01T11:40:23.647 に答える
1

@Tilakのソリューションは間違いなく1つの方法ですが、次の方法でこれを行うこともできますStyle.Triggers

以下に例を示します (Flagフラグを公開するパブリック プロパティであると仮定します)。

<Button Content="{StaticResource On1}">
    <Button.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Flag}" Value="false">
                    <Setter Property="Content" Value="{StaticResource Off1}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
于 2013-01-12T08:24:00.877 に答える