前台代码
<!-- 通过传递ElementName -->
<Button
x:Name="btn1"
Width="200"
Height="27"
Command="{Binding Command}"
CommandParameter="{Binding ElementName=btn1}" />
<!-- 通过传递自身 -->
<Button
Grid.Row="1"
Width="200"
Height="27"
Command="{Binding Command2}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}}" />
<!-- 通过传递Width Width是只读的,这种方法行不通,哪怕设置双向也不行,-->
<Button
Grid.Row="2"
Width="200"
Height="27"
Command="{Binding Command3}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Width,UpdateSourceTrigger=PropertyChanged}" />
后台代码
private DelegateCommand<Button> _Command;
public DelegateCommand<Button> Command =>
_Command ?? (_Command = new DelegateCommand<Button>(ExecuteCommand, CanExecuteCommand));
private void ExecuteCommand(object parameter)
{
var btn = parameter as Button;
btn.Width = 500;
}
private DelegateCommand<Button> _Command2;
public DelegateCommand<Button> Command2 =>
_Command2 ?? (_Command2 = new DelegateCommand<Button>(ExecuteCommand2));
private void ExecuteCommand2(object parameter)
{
var btn = parameter as Button;
btn.Width = 500;
}
private DelegateCommand<double> _Command3;
public DelegateCommand<double> Command3 =>
_Command3 ?? (_Command3 = new DelegateCommand<double>(ExecuteCommand3));
private void ExecuteCommand3(double parameter)
{
Application.Current.Dispatcher.Invoke(() =>
{
var width=parameter;
width = 500;
});
}
private bool CanExecuteCommand(object parameter)
{
return true;
}
第三种报错,因为Width是只读的,你可以传递一个实体,然后修改实体的属性,但是传递的参数本身应该是只读的,这是我个人的理解,如果能直接传递宽度实现宽度改变的,希望留下代码,一起交流
标签:传参,Command3,DelegateCommand,private,Command2,按钮,WPF,btn,parameter From: https://www.cnblogs.com/guchen33/p/17664283.html