想要一个控件在选中和未选中时表现出两种状态,然后就想到了ToggleButton的Checked状态。但是多余的状态不想要,于是找度娘......顺便学习一下自定义控件的状态。
1、首先引用:Microsoft.Expression.Interactions.dll
2、创建一个控件,前台xmal中定义好自定义的状态改变时的动画。
StateControl.xaml, 用到了 ExtendedVisualStateManager,添加了Checked和Uncheck两个状态。
<UserControl x:Class="SL_StateTest.Controls.StateControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d">
<Grid Background="CadetBlue" x:Name="LayoutRoot" Width="400" Height="400">
<VisualStateManager.CustomVisualStateManager>
<ei:ExtendedVisualStateManager/>
</VisualStateManager.CustomVisualStateManager>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CheckStates">
<VisualState x:Name="Checked">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="CheckState">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<Visibility>Visible</Visibility>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Unchecked"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid x:Name="CheckState" Visibility="Collapsed">
<Border Background="Brown"/>
<TextBlock Text="Checked" FontSize="50" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Grid>
</UserControl>
3、后台调用 ExtendedVisualStateManager
using System.Windows;
using System.Windows.Input;
using Microsoft.Expression.Interactivity.Core;
namespace SL_StateTest.Controls
{
public partial class StateControl
{
#region 属性
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(bool), typeof(StateControl), new PropertyMetadata(false, OnIsCheckedChanged));
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
#endregion
public StateControl()
{
InitializeComponent();
}
#region 事件
private static void OnIsCheckedChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var stateButton = obj as StateControl;
if (stateButton != null)
stateButton.OnIsCheckedChanged();
}
private void OnIsCheckedChanged()
{
ExtendedVisualStateManager.GoToElementState(LayoutRoot, IsChecked ? "Checked" : "Unchecked", false);
}
protected override void OnMouseLeftButtonUp(MouseButtonEventArgs args)
{
args.Handled = true;
IsChecked = !IsChecked;
base.OnMouseLeftButtonUp(args);
}
#endregion
}
}
DEMO: http://download.csdn.net/detail/wushang923/7493935