【问题标题】:How to perform command in WPF如何在 WPF 中执行命令
【发布时间】:2015-02-24 21:35:09
【问题描述】:

我正在使用MVVM棱镜,我的代码如下

     <ListBox x:Name="myListBox"  Grid.Row="0"
         ItemsSource="{Binding Path=_mySOurce}" 
         ScrollViewer.VerticalScrollBarVisibility="Auto" 
         SelectionChanged="myListBox_SelectionChanged">
    </ListBox>
    <Button Grid.Row="1" x:Name="btnSelect" 
     Command="{Binding Path=SaveCommand}" Content="Select" Margin="396,0,10,0"></Button>

在我的代码中我有

 public ICommand SaveCommand { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        this.SaveCommand = new DelegateCommand<object>(this.OnSaveClick, this.CanSaveExecute);       
    }

    private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }

    private void OnSaveClick(object arg)
    {

        MessageBox.Show("Performed Click");
    }
    private bool CanSaveExecute(object arg)
    {
        if (myListBox.SelectedIndex > 0)
            return true;

        else return false;
    }

我无法在选择更改事件中触发它。

我错过了什么?

【问题讨论】:

  • 在 myListBox_SelectionChanged 中触发 SaveCommand.Execute(parameter) ?
  • 如果您想在 SelectionChanged 处触发该命令,那么该事件的处理程序在哪里?

标签: c# wpf mvvm prism


【解决方案1】:

如果您在视图模型中处理 UI 事件,那么您根本就没有使用 MVVM!在视图模型中处理 UI 事件完全打破了 MVVM 提供的关注点分离。

但是,简短的回答是这样的:

private void myListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (SaveCommand.CanExecute(null)) SaveCommand.Execute(null);
}

更好的解决方案是将另一个属性添加到数据绑定到ListBox.SelectedItem 属性:

<ListBox x:Name="myListBox"  Grid.Row="0" SelectedItem="{Binding CurrentItem}"
    ItemsSource="{Binding Path=_mySOurce}" 
    ScrollViewer.VerticalScrollBarVisibility="Auto" 
    SelectionChanged="myListBox_SelectionChanged" />

然后,每当调用 SelectionChanged 事件时,都会调用该 CurrentItem 属性的设置器:

public YourDataType CurrentItem
{
    get { return currentItem; }
    set
    {
        currentItem = value;
        NotifyPropertyChanged("CurrentItem");
        if (SaveCommand.CanExecute(null)) SaveCommand.Execute(null);
    }
}

【讨论】:

  • 我还不相信更糟糕的事情:在属性设置器中产生副作用(如最后一个示例),或者不这样做,因为它是一种非常、非常方便且非常优雅的方式在 WPF/MVVM 中实现这种行为,一种“反应性”的东西(只要你不忘记隐藏的副作用)。这里有一个有趣的讨论:programmers.stackexchange.com/questions/82377/…
  • 也许你误读了你的链接帖子......在二传手中绝对没有提到“副作用”。你能想到这段代码有什么缺点吗,因为如果你愿意,我很想听听?
  • 一个颇有争议的问题是:当任何人设置一个属性时,您通常不会期望other,间接的事情发生在你背后。这种行为在设计时非常棒,而且你记住了这一点。但是,如果某些同事必须使用它,则行为并不明显,需要弄清楚。我自己也曾经发生过,在打扫卫生课的时候,忘记去二传手也在那里换衣服,然后事情就突然停止了。但我不会太担心它,因为正如我所说,我认为这种模式解决了它产生的更多问题。
猜你喜欢
  • 2019-06-30
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多