【问题标题】:Notification when a ListViewItem scrolls into viewListViewItem 滚动到视图中时的通知
【发布时间】:2018-09-28 19:14:08
【问题描述】:

下面的代码应该将一个项目滚动到视图中并将焦点设置到模板中的第一个子控件:

lv.ScrollIntoView(lv.SelectedItem);

var lvi = lv.SelectedListViewItem();

//get the item's template parent
var templateParent = lvi.GetFrameworkElementByName<ContentPresenter>();

if (templateParent != null)  <--but it's always null
{
   var ctrl = templateParent.FindVisualChildren<FrameworkElement>().First();
   ctrl.Focus();
}

问题是,如果ListViewItem 不可见,那么templateParent 为空,并且这段代码不起作用。当然,此代码仅在项目尚不可见时才有用。

有没有办法将项目滚动到视图中,然后在它进入视图时得到通知,这样模板将是非空的,以便执行ctrl.Focus() 代码?

【问题讨论】:

  • 我用 WPF 做了很多工作,但是使用触发器和 MVVM 不能解决问题?

标签: wpf


【解决方案1】:

您可以处理RequestBringIntoView 事件。请参考以下示例代码。

public MainWindow()
{
    InitializeComponent();
    lv.ItemsSource = Enumerable.Range(1, 100);
    lv.SelectedItem = 90;
    lv.ScrollIntoView(lv.SelectedItem);
    lv.RequestBringIntoView += Lv_RequestBringIntoView;
}

private void Lv_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
    var container = lv.ItemContainerGenerator.ContainerFromItem(lv.SelectedItem);
    if (container != null)
    {
        //...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 2015-12-08
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多