イメージとテキストを含むボタンを作成しようとしています。ただし、イメージは実行時にコード ビハインドによって変更される可能性があります。私の画像はpngで、全員が私のResourceDictionaryに次のように含まれています:
<BitmapImage x:Key="iconLogIn" UriSource="/Images/Icons/lock.png" />
したがって、私は Template や ContentTemplate を使用せずに、このスタイルから始めました。
<Style x:Key="MyTestButton" TargetType="{x:Type Button}">
<Setter Property="Height" Value="80" />
<Setter Property="Width" Value="100" />
</Style>
そして私のXAMLは次のとおりです。
<Button x:Name="cmdOption1" Style="{StaticResource MyTestButton}" Margin="8" Click="cmdOption1_Click">
<Image Source="{DynamicResource iconLogIn}" />
</Button>
次に、画像を変更するための私のコードは次のとおりです。
cmdOption1.Content = new Image() { Source = ((BitmapImage)FindResource("iconLogOut")) };
これまでのところ、これは機能します。
しかし、画像を保持するだけで、画像の下にテキストを配置したい。
だから私はこの投稿を読みました.HighCoreの答え、オプション#2は私の要件を満たすかもしれません. しかし、ここで新たな問題が発生します。
まず、これはシンプルなテンプレートを使用した新しいスタイルです
<Style x:Key="MyTestButton" TargetType="{x:Type Button}">
<Setter Property="Background" Value="#EEEEEE" />
<Setter Property="Foreground" Value="DarkSlateGray" />
<Setter Property="Height" Value="80" />
<Setter Property="Width" Value="100" />
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="FontSize" Value="12" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="DarkGray" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border>
<StackPanel>
<Image Source="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}}" Height="50" Width="50"/>
<ContentPresenter Grid.Row="0" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="DarkOrange" />
<Setter Property="OpacityMask" Value="#AA888888"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="Gray" />
<Setter Property="BorderBrush" Value="DarkGray" />
<Setter Property="Background" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Style>
私の新しい XAML は次のとおりです。
<Button x:Name="cmdOption1" Tag="{StaticResource iconLogIn}" Content="LOG IN" Style="{StaticResource MyTestButton}" Margin="8" Click="cmdOption1_Click" />
※Tag="{DynamicResource iconLogIn}" とも
そして、画像とテキストを変更する私のコードビハインド:
cmdOption1.Tag = new Image() { Source = ((BitmapImage)FindResource("iconLogOut")) };
cmdOption1.Content = "LOG OUT";
これにより、コンテンツテキストが「LOG IN」から「LOG OUT」に変わります。しかし、画像は表示されなくなり、画像の代わりに何も表示されず、エラーや例外もスローされません。
解決策と何が起こっているのか知りたいのですが、なぜ画像が変化せずに消えたのですか?
前もって感謝します。