Focus

De Banane Atomic
Aller à la navigationAller à la recherche

Set the focus in the view

Xaml.svg
<StackPanel FocusManager.FocusedElement="{Binding ElementName=tb}">
    <TextBox Name="tb" />

Set the focus in the code behind

Cs.svg
this.tb.Focus();

Set Focus from ViewModel

MainWindow.xaml
<Window xmlns:local="clr-namespace:MyNamespace"
    <TextBox local:FocusBehavior.IsFocused="{Binding FilterIsFocused, Mode=OneWay}">
MainVM.cs
FilterIsFocused = true;

private bool _filterIsFocused;
public bool FilterIsFocused
{
    get { return _filterIsFocused; }
    set
    {
        Set(() => FilterIsFocused, ref _filterIsFocused, value);
    }
}
FocusBehavior.cs
public static class FocusBehavior
{
    public static readonly DependencyProperty IsFocusedProperty =
        DependencyProperty.RegisterAttached(
            "IsFocused", //EXEMPT:GLOBALIZATION
            typeof(bool),
            typeof(FocusBehavior),
            new FrameworkPropertyMetadata(
                false,
                new PropertyChangedCallback(onIsFocusedPropertyChanged)));

    public static bool GetIsFocused(DependencyObject element)
    {
        //ArgumentCheck.IsNotNull(element, "element");

        return (bool)element.GetValue(IsFocusedProperty);
    }

    public static void SetIsFocused(DependencyObject element, bool value)
    {
        //ArgumentCheck.IsNotNull(element, "element");

        element.SetValue(IsFocusedProperty, value);
    }

    private static void onIsFocusedPropertyChanged(DependencyObject element, DependencyPropertyChangedEventArgs args)
    {
        UIElement target = element as UIElement;
        if (target == null)
        {
            return;
        }

        bool isFocused = (bool)args.NewValue;
        if (!isFocused)
        {
            return;
        }

        // Delay the call to allow the current batch of processing to finish before we shift focus.
        target.Dispatcher.BeginInvoke(
            (Action)(() =>
            {
                if (target.Focusable)
                {
                    target.Focus();

                }
            }), DispatcherPriority.Input);
    }
}