如何在WPF和MVVM中的控件上调用方法 [英] How to invoke a method on a control in WPF and MVVM

查看:286
本文介绍了如何在WPF和MVVM中的控件上调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我最近在单独使用WinForms之后一直在试验WPF和MVVM。我知道游戏的时间晚了!



我有一个窗口,有2个组合框用于过滤ListBox。我希望能够让用户在ListBox中进行选择,然后当他们删除过滤器时,他们的选择仍然存在,列表视图会自动滚动到它。



这可以通过调用ListBox的ScrollIntoView方法来完成,我通过在窗口后面的代码中使用事件来实现它。



有没有一种以更MVVM方式做到这一点的方法,或者事件是最好的方式吗?



我尝试过的方法:



Hi
I have been experimenting with WPF and MVVM recently after being solely WinForms for a long time. Bit late to the game I know!

I have a window that has 2 combo boxes that are used for filtering a ListBox. I'd like to be able to have the user make a selection in the ListBox then when they then remove the filters, their selection remains and the list view automatically scrolls to it.

This can be done by calling the ScrollIntoView method of the ListBox and I've achieved it by using an event in the code behind the window.

Is there a way to do this in a more MVVM way or is the event way the best way to do it?

What I have tried:

private void cBox_Selected(object sender, RoutedEventArgs e)
{
    errorListBox.ScrollIntoView(errorListBox.SelectedItem);
}







<ComboBox DockPanel.Dock="Left"
          Width="100"
          ItemsSource="{Binding AvailableFilters, UpdateSourceTrigger=PropertyChanged}"
          SelectedItem="{Binding SelectedFilter}"
          Name="cBox"
          SelectionChanged="cBox_Selected"
          >

推荐答案

Nathan在评论中给了我一个很好的答案
Nathan has given me a great answer in the comments


这篇关于如何在WPF和MVVM中的控件上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆