我正在创建一个用户控件,它是带有图像的切换按钮。当选中切换按钮和未选中切换按钮时,我具有单独的图像依赖属性。
Xaml:
<ToggleButton IsChecked="{Binding Checked, Mode=TwoWay}">
<Image>
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="{Binding CheckedImage}"></Setter>
<DataTrigger Binding="{Binding IsChecked}" Value="False">
<Setter Property="Source" Value="{Binding UncheckedImage}"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</ToggleButton>
后面的代码:
public partial class ImageToggleButton : UserControl
{
public ImageToggleButton()
{
InitializeComponent();
this.DataContext = this;
}
public bool Checked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
// Using a DependencyProperty as the backing store for IsChecked. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("Checked", typeof(bool), typeof(ImageToggleButton), null);
public ImageSource CheckedImage
{
get { return (ImageSource)base.GetValue(TrueStateImageProperty); }
set { base.SetValue(TrueStateImageProperty, value); }
}
// Using a DependencyProperty as the backing store for TrueStateImage. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TrueStateImageProperty =
DependencyProperty.Register("CheckedImage", typeof(ImageSource), typeof(ImageToggleButton), null);
public ImageSource UncheckedImage
{
get { return (ImageSource)base.GetValue(FalseStateImageProperty); }
set { base.SetValue(FalseStateImageProperty, value); }
}
// Using a DependencyProperty as the backing store for FalseStateImage. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FalseStateImageProperty =
DependencyProperty.Register("UncheckedImage", typeof(ImageSource), typeof(ImageToggleButton), null);
}
MainWindow:
<ImageToggleButton Checked="{Binding IsPlaying}" CheckedImage="{DynamicResource PauseIcon}" UncheckedImage="{DynamicResource PlayIcon}">
</ImageToggleButton>
是否可以将CheckedImage用作默认图像,以便如果我不提供UncheckedImage,则在选中和未选中状态下都将显示CheckedImage?
答案 0 :(得分:1)
您可以为PropertyChangedCallback
属性注册一个CheckedImage
,该属性设置另一个属性的值:
public static readonly DependencyProperty TrueStateImageProperty =
DependencyProperty.Register("CheckedImage", typeof(ImageSource), typeof(ImageToggleButton),
new PropertyMetadata(new PropertyChangedCallback(OnPropChanged)));
private static void OnPropChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ImageToggleButton tb = (ImageToggleButton)d;
if (tb.UncheckedImage == null)
tb.UncheckedImage = (ImageSource)e.NewValue;
}
顺便说一句,您应该遵循依赖项属性的命名约定:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/custom-dependency-properties