WPF设置传参、点击按钮改变长度
前台代码
<!-- 通过传递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是只读的,你可以传递一个实体,然后修改实体的属性,但是传递的参数本身应该是只读的,这是我个人的理解,如果能直接传递宽度实现宽度改变的,希望留下代码,一起交流
本文作者:孤沉
本文链接:https://www.cnblogs.com/guchen33/p/17664283.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步