笔记2:WPF Command命令使用

本文详细介绍了WPFCommand在WPF应用程序中的使用方法,包括如何通过相对源绑定找到父级ListBox并触发事件,以及如何使用CommandParameter双向更新控件数据。同时,探讨了如何将指定控件对象作为参数传递给Command。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

笔记:WPFCommand命令使用:.

1、列表按钮绑定事件使用

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=DataContext.But_click}" CommandParameter="{Binding Name,Mode=TwoWay}"
绑定按钮点击Command,找到对象的父级容器,类型指定为ListBox,触发事件为DataContext.But_click,返回父级容器数据中的Name,双向更新,Frame 作为弹窗控件用,当命令触发时向frame中添加控件改变Height达到类似于弹窗的效果

		<ListBox Name="l" Margin="30,0,30,60" ItemsSource="{Binding MyProperty}">
                <ListBox.ItemTemplate >
                    <DataTemplate >
                        <StackPanel Orientation="Vertical">
                            <StackPanel Orientation="Horizontal">
                                <Label Content="{Binding Name}" Foreground="Black"/>
                                <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, 
                                Path=DataContext.But_click}"
                                 CommandParameter="{Binding Name,Mode=TwoWay}" >点击</Button>
                            </StackPanel>
                            <StackPanel >
                                <Frame  Content="{Binding UC}" Height="{Binding Height}" Background="Yellow" ></Frame>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

使用方法

//1
<Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=容器类型},
 Path=绑定命令名称}" CommandParameter="{Binding 需要返回的数据,Mode=TwoWay}"/>
//2
<Button   Command="{Binding ElementName=父节点名称,Path=绑定命令名称}" 
CommandParameter="{Binding 需要返回的数据,Mode=TwoWay}"/>

2、Command命令绑定传递指定控件对象

Xaml代码

<Grid Name="test">
        <Label Name="image_nasme" Content="你找到我了"/>
        <StackPanel>
            <ListBox >
            </ListBox>
        </StackPanel>
        <Button Height="100" Command="{Binding But_click}" CommandParameter="{Binding ElementName=test}"/>
    </Grid>

Csharp代码

public ICommand But_click
        {
            get
            {
               return  new BaseCommand(o=> {
                   foreach (var item in ((Grid)o).Children)
                   {
                       MessageBox.Show(item.GetType().ToString());
                   }
                });
            }
        }

ViewModel层打断点,名为test的Grid对象成功传递过来了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值