笔记2: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());
}
});
}
}