转换为DependencyProperty

时间:2015-05-27 23:15:34

标签: c# wpf xaml

我有一个问题,有人可以帮助转换此代码(在代码隐藏中使用)以供dependyProperty使用吗?

此代码将焦点放在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();
                }
            }
        }
    }

具体来说,我想在我的XAML中编写类似:local:FocusFirstElement.Focus="True"的内容,而不是为每个列表视图编写此代码。

1 个答案:

答案 0 :(得分:1)

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

首先,创建一个附加属性。使用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中)并注册或取消注册ListView中包含的depObj上的相应事件。然后,您将使用现有代码来设置焦点。类似的东西:

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

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