Command可以根據CommandParameter傳參
關鍵代碼
public ICommand SubmitCommand => _submitCommand;
private RelayCommand _submitCommand = new RelayCommand(new Action<object>(ShowMessage));
private static void ShowMessage(object obj)
{MessageBox.Show(obj.ToString());
}
<TextBox Name="textBox1"></TextBox>
<Button Command="{Binding SubmitCommand}" CommandParameter="{Binding ElementName=textBox1,Path=Text}" Content="提交參數"></Button>
也可以這樣綁定
<Label Grid.Row="0">姓名:</Label>
<TextBox Name="name" Grid.Row="0" Grid.Column="1" Text="{Binding Person.Name}"></TextBox>
<Label Grid.Row="1">年齡:</Label>
<TextBox Name="age" Grid.Row="1" Grid.Column="1" Text="{Binding Person.Age}"></TextBox>
<Button Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Command="{Binding SubmitCommand}" CommandParameter="{Binding Person}" Content="提交參數"></Button>
示例代碼
https://github.com/zLulus/NotePractice/tree/dev3/WPF/WpfDemo/Command
Command與Click的關系
Command用于后臺操作,click用于前臺展示、交互,可以共存