ToggleButton 솔루션 (다른 사용자의 답변에 제안 된대로)이 가장 적합 할 것입니다. 그럼에도 불구하고 나는 완전성을 위해 또 다른 접근법을 게시하고있다.
XAML은 :
<Window x:Class="WpfTestBench.PlayButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfTestBench="clr-namespace:WpfTestBench"
Title="Play button sample">
<Button Width="40" Height="40" Click="Button_OnClick">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Stroke="Black" />
<Image Source="Play.png" Visibility="{Binding Path=IsPlaying,
Converter={wpfTestBench:BoolToVisibilityConverter},
ConverterParameter={x:Static Visibility.Hidden}}" />
<Image Source="Pause.png" Visibility="{Binding Path=IsPlaying,
Converter={wpfTestBench:BoolToVisibilityConverter},
ConverterParameter={x:Static Visibility.Visible}}" />
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
는
은 Codebehind가 :
는
using System.ComponentModel;
using System.Windows;
namespace WpfTestBench
{
public partial class PlayButton
{
public PlayButton()
{
InitializeComponent();
DataContext = new SampleContext();
}
private void Button_OnClick(object sender, RoutedEventArgs e)
{
var context = DataContext as SampleContext;
if (context == null)
return;
context.IsPlaying = !context.IsPlaying;
}
}
public class SampleContext : INotifyPropertyChanged
{
private bool _isPlaying;
public bool IsPlaying
{
get { return _isPlaying; }
set
{
if (_isPlaying == value)
return;
_isPlaying = value;
OnPropertyChanged("IsPlaying");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
변환기 :
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace WpfTestBench
{
public class BoolToVisibilityConverter : MarkupExtension, IValueConverter
{
private static BoolToVisibilityConverter _instance;
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var visibility = Visibility.Hidden;
if (parameter != null)
visibility = (Visibility)parameter;
return visibility == Visibility.Visible
? (((bool)value) ? Visibility.Visible : Visibility.Hidden)
: (((bool)value) ? Visibility.Hidden : Visibility.Visible);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
#endregion
public override object ProvideValue(IServiceProvider serviceProvider)
{
return _instance ?? (_instance = new BoolToVisibilityConverter());
}
}
}
매우 유용하고 완벽했다! –