【发布时间】:2019-03-28 16:05:22
【问题描述】:
我正在创建一个用户控件,它是一个带有图像的切换按钮。当检查切换按钮以及未选中切换按钮时,我具有单独的依赖关系属性。
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);
}
主窗口:
<ImageToggleButton Checked="{Binding IsPlaying}" CheckedImage="{DynamicResource PauseIcon}" UncheckedImage="{DynamicResource PlayIcon}">
</ImageToggleButton>
是否可以使用 CheckedImage 作为默认图像,这样如果我不提供 UncheckedImage,那么在选中和未选中状态下都会显示 CheckedImage?
【问题讨论】:
-
您可以只为您的按钮使用模板并使用触发器来分配图像,否则您重新创建的 ToggleButton 功能比原始设计少。 10 次中有 9 次不需要 UC。就像你写的一样,但默认使用未选中的图像,然后使用样式来分配选中的图像。希望这是有道理的。
-
感谢@XAMlMAX 的想法
标签: c# wpf data-binding