一旦VisualState“Prepared”被激活,我视图中的一个控件应将AttachedProperty“FocusClaim”设置为true。 msdn文档说我可以使用AttachedProperties,我只需要在括号中给出ownerType和PropertyName。但这样做会导致异常: System.InvalidOperationException:无法为给定对象解析TargetProperty“(my:VisualStateMacro.FocusClaim)”。
那是带动画的VisualState:
<VisualState x:Name="Prepared">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Foo"
Storyboard.TargetProperty="(my:VisualStateMacro.FocusClaim)">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<system:Boolean>True</system:Boolean>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
实际目标:
<TextBox my:VisualStateMacro.FocusClaim="False" x:Name="Foo"/>
一行(在MSdn上找到PropertyPath for Animation Targets)虽然与同一网站上给出的示例有些冲突:
propertyName必须是Storyboard.TargetName指定的类型上存在的属性。
还有几行:
<animation Storyboard.TargetProperty="(ownerType.propertyName)" .../>
我允许使用自己的AttachedProperty作为目标,还是我必须使用Control类中的属性?
这是我定义AttachedProperty的方式:
public class VisualStateMacro
{
public static bool GetFocusClaim( DependencyObject obj )
{
return (bool) obj.GetValue( FocusClaimProperty );
}
public static void SetFocusClaim( DependencyObject obj, bool value )
{
obj.SetValue( FocusClaimProperty, value );
}
public static readonly DependencyProperty FocusClaimProperty =
DependencyProperty.RegisterAttached( "FocusClaim", typeof( bool ),
typeof( VisualStateMacro ),
new PropertyMetadata( false, HandleFocusClaimChanged ) );
private static void HandleFocusClaimChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var focusTarget = d as Control;
if(focusTarget==null)return;
var shouldReceiveFocusNow = (bool)e.NewValue;
if (shouldReceiveFocusNow)
{
focusTarget.Focus();
}
}
}