0624-InteractionRequest ObservableCollection DelegateCommand

MVVM

在MVVM设计模式中,View产生的操作由Command传递到ViewModel,View上的数据显示则由 Data Binding 负责,而ViewModel对View的操作,则由InteractionRequest完成。

public InteractionRequest<INotification> WindowEnvironmentSettingEditViewRequest { get; set; }

WindowEnvironmentSettingEditViewRequest.Raise(new Notification { Content = new ChildWindowContent { Param = sendParam, ParentWindow = Application.Current.MainWindow } });

这是ViewModel的代码,里面通过调用InteractionRequest的Raise方法,去通知View。

<prism:InteractionRequestTrigger SourceObject="{Binding WindowEnvironmentSettingEditViewRequest,Mode=OneWay}">

 </prism:InteractionRequestTrigger>

ObservableCollection<T> 类    表示一个动态数据集合,在添加项、移除项或刷新整个列表时,此集合将提供通知。

在许多情况下,所使用的数据是对象的集合。 例如,数据绑定中的一个常见方案是使用 ItemsControl(如 ListBoxListView 或 TreeView)来显示记录的集合。

可以枚举实现 IEnumerable 接口的任何集合。 但是,若要设置动态绑定,以便集合中的插入或删除操作可以自动更新 UI,则该集合必须实现 INotifyCollectionChanged 接口。 此接口公开 CollectionChanged 事件,只要基础集合发生更改,都应该引发该事件。

WPF 提供 ObservableCollection<T> 类,它是实现 INotifyCollectionChanged 接口的数据集合的内置实现。

还有许多情况,我们所使用的数据只是单纯的字段或者属性,此时我们需要为这些字段或属性实现INotifyPropertyChanged接口,实现了该接口,只要字段或属性的发生了改变,就会提供通知机制

https://blog.csdn.net/qing2005/article/details/6601199

首先引用  Microsoft.Practices.Prism

MVVM模式代码如下:

XAML代码:

<!-- 无参方式 -->
<Button Content="Test Command" Command="{Binding TestCommand}" />

<!-- 将自己作为参数 -->
<Button Content="Test Command2" Command="{Binding TestCommand2}" CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}" >

<!-- 将父元素作为参数 -->
<Button Content="Test Command3" Command="{Binding TestCommand3}" CommandParameter="{Binding RelativeSource={x:Static RelativeSource.TemplatedParent}}" >

后台代码:

// code-behind构造函数中添加:

this.DataContext = new ViewModel();

ViewModel代码:

// ViewModel 构造函数
public ViewModel()
{    CallCOmmand1 = new DelegateCOmmmand(Call1);
    CallCOmmand2 = new DelegateCOmmmand<Object>(Call2);
    CallCOmmand3 = new DelegateCOmmmand<Object>(Call3);
}

// 命令声明
public DelegateCommand CallCommand { get; private set; }
public DelegateCommand<Object> CallCommand2 { get; private set; }
public DelegateCommand<Object> CallCommand3 { get; private set; }

// 命令实现
public void Call1()
{
}

public void Call2( Object obj )
{
    Button button = obj as Button;
}

public void Call3( Object obj )
{
    ParentType parent = obj as ParentType;
}

ICommand成员如下:

  a:CanExecuteChanged事件和CanExecute方法被用来确定command所施加控件的视觉状态,它们是这样工作的:当某command施加于某控件时,控件会调用CanExecute方法,来确定初始的视觉状态,假设调用者是button,如果CanExecute方法返回false,button会被禁用。button同时也会订阅CanExecuteChanged事件。当触发CanExecuteChanged事件时,会再次调用CanExecute以确定是否需要修改视觉状态。

  b:Execute方法比较直白:当需要执行某些行为操作时,控件会调用它。例如,当按下按钮时。

猜你喜欢

转载自blog.csdn.net/qq_30807313/article/details/93492511
今日推荐