【问题标题】:Conection MVVM Light with SelectionChanged使用 SelectionChanged 连接 MVVM 灯
【发布时间】:2017-02-01 20:01:59
【问题描述】:

我正在 UWP 中创建应用程序,但我有疑问。 我可以以某种方式将 MVVM Light 与 SelectionChanged 事件(例如 ListView)或其他事件连接起来吗? 我希望当我单击 ListView 中的某个项目时,我会调用 SelectionChanged。

我该怎么做?

【问题讨论】:

  • 关于这个问题的任何更新?如果您对此问题有任何其他疑虑,请随时告诉我。

标签: binding uwp mvvm-light


【解决方案1】:

您可以在ViewModel中编写Method,并使用x:bind连接ViewModel。

MVVMLight的方法用在WPF中,无法在Method中绑定事件。

UWP 可以使用x:bind 将 UI 事件绑定到 ViewModel。

样本:

XAML:

<ListView SelectionChanged = "{x:bind view.SelectionChanged }"/>

XAML.cs:

private ViewModel View{set;get;}

视图模型:

public void SelectionChanged()
{

}

您可以使用单击 ListViewItem 时将运行的 ItemClick 事件。

【讨论】:

    【解决方案2】:

    在你的视图模型里面有一些 *.cs

    public class RelayCommand : ICommand
    {
        private Predicate<object> _canExecute;
        private Action<object> _execute;
    
        public RelayCommand(Predicate<object> canExecute, Action<object> execute)
        {
            this._canExecute = canExecute;
            this._execute = execute;
        }
    
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    
        public bool CanExecute(object parameter)
        {
            return _canExecute(parameter);
        }
    
        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
    
    public class MyViewModel
    {
        private ICommand _doSelectionChangedCommand;
        public ICommand DoSelectionChangedCommand
        {
            get
            {
                if (_doSelectionChangedCommand == null)
                {
                    _doSelectionChangedCommand = new RelayCommand(
                        p => this.CanSelectionChanged,
                        p => this.DoSomeImportantMethod());
                }
                return _doSomething;
            }
        }
    }
    

    在您看来Somemthing.xaml --对于命名空间

    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    

    --那就下到你的控件,我们以Combobox为例

    <ComboBox ... />
       <i:Interaction.Triggers>
        <EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding DoSelectionChangedCommand}"/>              
        </EventTrigger>
    </i:Interaction.Triggers>
    </ComboBox>
    

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 1970-01-01
      • 2015-04-17
      • 2018-05-03
      • 1970-01-01
      • 2013-04-03
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多