目录格式
实现的功能
XAML 文件
<Grid> <StackPanel> <!-- 数据绑定 --> <TextBox Width="300" x:Name="TextBox1" Height="30" Margin="15" Text="{Binding SearchText}"/> <!-- 命令绑定 --> <Button Content="展示" Width="50" Height="30" Margin="15" Command="{Binding SignInCommand}" /> </StackPanel> </Grid>
baseCommon NotifyPropertyChanged.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; namespace dataEventBinding.baseCommon { public class NotifyPropertyChanged : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { }; // 通知属性更改 <param name="propertyName" /> protected void RaisePropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
baseCommon RelayCommand.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace dataEventBinding.baseCommon { class RelayCommand : ICommand { public event EventHandler CanExecuteChanged = (sender, e) => { }; private Action mAction; public RelayCommand(Action action) { this.mAction = action; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { mAction.Invoke(); } } }
ViewModels MainViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace dataEventBinding.ViewModels { public class MainViewModel : baseCommon.NotifyPropertyChanged { public MainViewModel() { SignInCommand = new baseCommon.RelayCommand(() => { MessageBox.Show(searchText); }); } private string searchText; // 发布方法 供外面使用 public ICommand SignInCommand { get; private set; } public string SearchText { get { return searchText; } set { searchText = value; RaisePropertyChanged(nameof(searchText)); } } } }
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace dataEventBinding.Views { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { // 创建对象并赋值给 window.DataContext public ViewModels.MainViewModel m = new ViewModels.MainViewModel(); public MainWindow() { InitializeComponent(); m.SearchText = "water"; this.DataContext = m; } } }