【发布时间】:2021-07-10 16:12:20
【问题描述】:
事件管理如何使用 MVVM 模式在 WPF 中工作?我真的应该避免使用直接事件管理吗? 示例:正在构建这样的视图:
<Grid>
<Button Click="GO_Button_Click" Content="Go" Margin="39,143,503,250"/>
<TextBox x:Name="outputFolder" Margin="321,182,35,211" Text="{Binding outputFolderPath}"/>
</Grid>
拥有这样的视图模型:
using System.ComponentModel;
using System.Windows;
namespace FirstWpfApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
#region variables
public string outputFolderPath { get; set; }
#endregion
#region events
private void GO_Button_Click(object sender, RoutedEventArgs e)
{
outputFolderPath = "Some data";
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(outputFolderPath)));
}
#endregion
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
难道我不能更好地实现 MVVM 模式,避免从视图中调用“GO_Button_Click”方法吗?
【问题讨论】:
标签: c# wpf design-patterns mvvm desktop-application