public static class FocusOnLoad
{
public static bool GetCanFocusOnLoad(DependencyObject obj)
{
return (bool)obj.GetValue(CanFocusOnLoadProperty);
}
public static void SetCanFocusOnLoad(DependencyObject obj, bool value)
{
obj.SetValue(CanFocusOnLoadProperty, value);
}
// Using a DependencyProperty as the backing store for CanFocusOnLoad. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CanFocusOnLoadProperty =
DependencyProperty.RegisterAttached("CanFocusOnLoad", typeof(bool), typeof(FocusOnLoad), new PropertyMetadata(FocusOnLoadChanged));
private static void FocusOnLoadChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as FrameworkElement;
if (element != null)
{
element.Loaded += delegate
{
element.Focus();
};
}
}
}<TextBox behaviors:FocusOnLoad.CanFocusOnLoad="True"
VerticalAlignment="Center"
Width="200"/>public class FocusOnLoadBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
this.AssociatedObject.Loaded += this.OnLoaded;
}
protected override void OnDetaching()
{
this.AssociatedObject.Loaded -= this.OnLoaded;
}
private void OnLoaded(object sender, System.Windows.RoutedEventArgs e)
{
this.AssociatedObject.Focus();
}
}<TextBox behaviors:FocusOnLoad.CanFocusOnLoad="True"
VerticalAlignment="Center"
Width="200">
<i:Interaction.Behaviors>
<behaviors:FocusOnLoadBehavior />
</i:Interaction.Behaviors>
</TextBox><Style TargetType="TextBox">
<Setter Property="behaviors:FocusOnLoad.CanFocusOnLoad"
Value="True" />
</Style>- Casting
The PropertyChanged callback will give you the dependency object. This is the element in XAML, where we set the property. But to access some property or to invoke a method we need to cast it to UIElement or FrameworkElement. But in Behavior, it is possible to mention the datatype – Behavior. So no more casting. Using AssociateObject all the members of the type can be accessed. In above case, I mentioned it as FrameworkElement, since the Loaded event coming from that.
- Visual Designer Behaviors can be drag and drop into particular object using Blend, where Attached properties are not.You can drag and drop behavior objects on other behavior objects to set up a hierarchy, and you can set properties on objects already in the designer through the properties window.
https://wpfplayground.wordpress.com/2014/12/16/attached-properties-vs-behaviors/