我有一个带有列表框的XAML视图:
<control:ListBoxScroll ItemSource="{Binding Path=FooCollection}"
SelectedItem="{Binding SelectedFoo, Mode=TwoWay}"
ScrollSelectedItem="{Binding SelectedFoo}">
<!-- data templates, etc. -->
</control:ListBoxScroll>
Run Code Online (Sandbox Code Playgroud)
所选项目绑定到我视图中的属性.当用户选择列表框中的项目时,视图模型中的SelectedFoo属性会更新.当我在视图模型中设置SelectedFoo属性时,在列表框中选择了正确的项目.
问题是,如果代码中设置的SelectedFoo当前不可见,我需要另外调用ScrollIntoView列表框.由于我的ListBox在视图中,而我的逻辑在我的视图模型中...我找不到方便的方法来做到这一点.所以我扩展了ListBoxScroll:
class ListBoxScroll : ListBox
{
public static readonly DependencyProperty ScrollSelectedItemProperty = DependencyProperty.Register(
"ScrollSelectedItem",
typeof(object),
typeof(ListBoxScroll),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(onScrollSelectedChanged)));
public object ScrollSelectedItem
{
get { return (object)GetValue(ScrollSelectedItemProperty); }
set { SetValue(ScrollSelectedItemProperty, value); }
}
private static void onScrollSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var listbox = d as ListBoxScroll;
listbox.ScrollIntoView(e.NewValue);
}
}
Run Code Online (Sandbox Code Playgroud)
它基本上公开了一个新的依赖属性ScrollSelectedItem,它绑定到SelectedFoo我的视图模型上的属性.然后我挂钩属性更改依赖属性的回调并将新选择的项目滚动到视图中.
有没有其他人知道在视图模型支持的XAML视图上调用用户控件上的函数的更简单方法?这有点像:
WPF,类似浏览器的应用.
我有一个包含ListView的页面.在调用PageFunction后,我向ListView添加一行,并希望将新行滚动到视图中:
ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
if (item != null)
ScrollIntoView(item);
Run Code Online (Sandbox Code Playgroud)
这有效.只要新线在视图中,线就会得到它应该的焦点.
问题是,当线条不可见时,事情不起作用.
如果该行不可见,则生成的行没有ListViewItem,因此ItemContainerGenerator.ContainerFromIndex返回null.
但如果没有该项目,如何将该行滚动到视图中?有没有办法滚动到最后一行(或任何地方)而不需要ListViewItem?