一樣是使用 Prism & MEF,Command 的部分是用 Prism.Commands
小小的寫個 Demo,輸入名字送出會透過 Command 執行 function 並且傳遞 CommandParameter 的值,顯示 Hello XXX,若沒輸入名字則會顯示 Hello Stranger
Xmal
<Button Content="Submit" Command="{Binding btnCommand}" CommandParameter="{Binding ElementName=tbName}" />
<sdk:Label Content="Hello" />
<sdk:Label Name="lbName" Content="{Binding Name}" />
xmal.cspublic View()
{
InitializeComponent();
ViewModel model = new ViewModel();
this.DataContext = model;
}
ViewModelBase.cs (只是把值變更時的 PropertyChanged 抽出來)
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ViewModel.cs
public class ViewModel : ViewModelBase
{
public ICommand btnCommand { get; private set; }
private bool CanSubmit(object arg) { return true; }
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public ViewModel()
{
this.btnCommand = new DelegateCommand<object>(this.Exec, this.CanSubmit);
}
private void Exec(object o)
{
TextBox tb = (TextBox)o;
if (String.IsNullOrEmpty(tb.Text))
{
Name = "Stranger";
}
else
{
Name = tb.Text;
}
}
}
Sample Code 下載 - file name: Demo_ICommand.rar

沒有留言:
張貼留言