avechuche
avechuche

Reputation: 1560

Convert to DependencyProperty

I have a question, someone could help transform this code (used in codebehind ) for use by dependyProperty ?

This code gives the focus to the first item of listview . THX!!!!!!

    private void ItemContainerGeneratorOnStatusChanged(object sender, EventArgs eventArgs)
    {
        if (lvResultado.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            var index = lvResultado.SelectedIndex;
            if (index >= 0)
            {
                var item = lvResultado.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
                if (item != null)
                {
                    item.Focus();
                }
            }
        }
    }

Specifically, I want to write something like: local:FocusFirstElement.Focus="True" in my XAML instead of writing this code for every list view.

Upvotes: 1

Views: 493

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61349

What you are is really an attached behavior, which is implemented via an attached property which is really a special dependency property (which you seem to have hit upon already).

First, create an attached property. This is most easliy accomplished using the propa snippet:

    public static bool GetFocusFirst(ListView obj)
    {
        return (bool)obj.GetValue(FocusFirstProperty);
    }

    public static void SetFocusFirst(ListView obj, bool value)
    {
        obj.SetValue(FocusFirstProperty, value);
    }


    public static readonly DependencyProperty FocusFirstProperty =
        DependencyProperty.RegisterAttached("FocusFirst", typeof(bool), 
           typeof(ListViewExtension), new PropertyMetadata(false));

I'm assuming this is in a static class called ListViewExtenstion. Then, handle the property changed event:

    public static readonly DependencyProperty FocusFirstProperty =
        DependencyProperty.RegisterAttached("FocusFirst", typeof(bool), 
           typeof(ListViewExtension), new PropertyMetadata(false, HandleFocusFirstChanged));

 static void HandleFocusFirstChanged(
  DependencyObject depObj, DependencyPropertyChangedEventArgs e)
  {
  }

In that handler you would check the current value (in e) and register or deregister for the appropriate event on the ListView contained in depObj. Then you would use your existing code to set the focus. Something like:

 static void HandleFocusFirstChanged(
  DependencyObject depObj, DependencyPropertyChangedEventArgs e)
  {
     ListView lv = (ListView)debObj;

     if ((bool)e.NewValue)
        lv.StatusChanged += MyLogicMethod;
  }

Upvotes: 1

Related Questions