笔记2:WPF Command命令使用

笔记: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对象成功传递过来了

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值