简单通用应用程序MVVM的例子不工作的按钮点击
本文关键字:工作 按钮 应用程序 MVVM 简单 | 更新日期: 2023-09-27 18:12:38
文本绑定良好。这很简单。如果你发现少了什么,请告诉我。现在,当我点击按钮SHOWMESSAGE没有被调用。我遵循了这个例子,唯一不同的是它是WPF,并在XAML而不是代码中设置虚拟机。看到遗漏了什么吗?
http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-AbsoluteXAML
<StackPanel>
<TextBlock Text="Get Quote Questions" Style="{StaticResource TitleTextBlockStyle}" />
<TextBox Text="{x:Bind ViewModel.City}" PlaceholderText="City " />
<TextBox Text="{x:Bind ViewModel.State}" PlaceholderText="State Code " />
<TextBox Text="{x:Bind ViewModel.ZipCode}" PlaceholderText="Zip Code " />
<Button Content="Get Quote Questions" Command="{Binding ViewModel.GetQuoteQuestionsCommand, Mode=OneWay}" />
</StackPanel>
背后的代码:
public GetQuoteQuestionsVm ViewModel { get; private set; }
public GetQuoteQuestions()
{
this.InitializeComponent();
var vm = new GetQuoteQuestionsVm();
this.ViewModel = vm;
}
ViewModel:
public class GetQuoteQuestionsVm : NotifyPropertyChanged
{
private string city;
public string City
{
get { return city; }
set { Set(ref city, value); }
}
private ICommand getQuoteQuestionsCommand;
public ICommand GetQuoteQuestionsCommand
{
get
{
return getQuoteQuestionsCommand;
}
set
{
getQuoteQuestionsCommand = value;
}
}
public GetQuoteQuestionsVm()
{
City = "Woodbridge";
GetQuoteQuestionsCommand = new RelayCommand(new Action<object>(ShowMessage));
}
public async void ShowMessage(object obj)
{
var dialog = new MessageDialog("Your message here");
await dialog.ShowAsync();
}
}
RelayCommand:
public class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (parameter != null)
{
_action(parameter);
}
else
{
_action("Hello World");
}
}
}
几点建议:
1)而不是:
命令= "{绑定视图模型。GetQuoteQuestionsCommand, Mode=OneWay}"/>
试题:命令= "{绑定视图模型。GetQuoteQuestionsCommand} "/>
2)不要"滚动你自己的"RelayCommand。使用MVVM库,如MvvmLight,并使用那里提供的RelayCommand。