Convert to DependencyProperty

本文关键字:DependencyProperty to Convert | 更新日期: 2023-09-27 17:50:59

我有一个问题,有人可以帮助转换这个代码(在代码背后使用)使用的依赖属性?

这段代码将焦点放在listview的第一项上。谢谢! !

    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();
                }
            }
        }
    }

具体来说,我想在我的XAML中写这样的东西:local:FocusFirstElement.Focus="True",而不是为每个列表视图写这段代码。

Convert to DependencyProperty

你实际上是一个附加行为,它是通过附加属性实现的,这实际上是一个特殊的依赖属性(你似乎已经想到了)。

首先,创建一个附加属性。这是使用propa代码段最容易实现的:

    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));

我假设这是在一个静态类称为ListViewExtenstion。然后,处理属性更改事件:

    public static readonly DependencyProperty FocusFirstProperty =
        DependencyProperty.RegisterAttached("FocusFirst", typeof(bool), 
           typeof(ListViewExtension), new PropertyMetadata(false, HandleFocusFirstChanged));
 static void HandleFocusFirstChanged(
  DependencyObject depObj, DependencyPropertyChangedEventArgs e)
  {
  }

在该处理程序中,您将检查当前值(在e中)并在depObj中包含的ListView上注册或取消注册适当的事件。然后,您将使用现有代码来设置焦点。比如:

 static void HandleFocusFirstChanged(
  DependencyObject depObj, DependencyPropertyChangedEventArgs e)
  {
     ListView lv = (ListView)debObj;
     if ((bool)e.NewValue)
        lv.StatusChanged += MyLogicMethod;
  }
相关文章:
  • 没有找到相关文章