正确使用MVVM和命令

时间:2015-02-13 10:32:33

标签: c# wpf xaml mvvm command

如何使用ICommand与MVVM的接口?

在视图中,我添加了DataContext(我的ViewModel : INotifyPropertyChanged),并将控件的属性 - IsInterminate的进度条绑定到我的ViewModel的属性。我ViewModel的此属性不是静态的,因此我需要ViewModel的实例。

我的问题是:如何在命令方法中更新此ViewModel实例(绑定到查看进度条的属性)(此方法为ViewModel)?< / p>

<StatusBar Grid.Row="1">
    <StatusBar.DataContext>
        <viemodel:EventsViewModel x:Name="evm"/>
    </StatusBar.DataContext>
    <Label x:Name="lbStatusLabel" Width="70" Height="40" Content="{Binding EventsCollection.Count}"/>
    <Separator />
    <ProgressBar x:Name="pbProgress" Width="300" Height="40" IsIndeterminate="{Binding Pennding}"/>
</StatusBar>

class EventsViewModel : ViewModel
{
    private static FWatch fw;
    private static string fileName;
    private static string pathToFile;
    private static string pathToDirectory;

    public EventsViewModel()
    {
        _startCommand = new RelayCommand(OpenFileCommand);
    }

    private ICommand _startCommand;
    public ICommand StartCommand
    {
        get { return _startCommand; }
    }

    private static ObservableCollection<Event> _eventsCollection = new ObservableCollection<Event>();
    public static ObservableCollection<Event> EventsCollection
    { 
        get { return _eventsCollection; }
    }

    private static string _buttonContent = "Open file";        
    public string ButtonContent
    {
        get { return _buttonContent; }
        set
        {
            _buttonContent = value;
            NotifyPropertyChanged();
        }
    }

    private bool _pending = false;
    public bool Pennding
    {
        get { return _pending; }
        set
        {
            _pending = value;
            NotifyPropertyChanged();
        }
    }

    private void OpenFileCommand()
    { 
        // Here I want to update field _pennding - is it right? Or should I delegate it?
        // Should I update `Pendding` property of `ViewModel` where is command's method or I should do it in behind-code of view?
    }
} 

3 个答案:

答案 0 :(得分:0)

您应该从Command处理程序设置“Pending”属性。在您的情况下,它是OpenFileCommand。

private void OpenFileCommand()
{ 
     this.Pending = true;
}

答案 1 :(得分:0)

您必须使用一些命令基础结构组件。有几个可用。 例如MVVM Light是一个很好的。 看看这里有一些提示: How to use RelayCommand with the MVVM Light framework

但是您需要在表单上使用一个按钮,并将其绑定到命令以触发ViewModel上的操作。

应该在Pending中操纵

ViewModel。绑定负责其余部分。 提高&#34;财产变化&#34;我使用的通知:

this.OnPropertyChanged(() => Breedte);

即。更改的属性在最终引发的事件中传递。我在你的代码中看不到这一点。 你至少需要类似上面的东西或

NotifyPropertyChanged("propertyName");

否则框架不知道改变了什么以及如何调整GUI。

答案 2 :(得分:0)

现在我知道了。

在xaml中使用datacontext会创建实例。我使用了dataconytext标签3次,我有3个我的模型实例。