[英]DelegateCommand in Listview with UserControl
如何在带用户控件的Lisview中使用DelegateCommand? 在我的Listview中,我像这样使用它:
<ListView x:Name="peopleListBox">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<UserControls:ItemTemplateControl QuestionText="{Binding parametr}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView>
我在UserControl中尝试:
<Button Content="Click" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/>
和这个:
<Button Content="Click" Command="{Binding Path=OpenCommand, ElementName=peopleListBox}"/>
这两个代码都不起作用。
UserControl:
<UserControl
x:Class="App13.UserControls.ItemTemplateControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local1="using:App13"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid>
<Button Content="Click" Foreground="Black" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/>
</Grid>
</UserControl>
您不能在用户控件的XAML中使用peopleListBox
。 它是在父控件中定义的字段,在子控件中不可访问。
您提供的代码对我有用(列表视图模板按钮单击会调用命令处理程序):
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListView x:Name="peopleListBox">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Button Command="{Binding
DataContext.OpenCommand,
ElementName=peopleListBox}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
我使用的视图模型:
public class VM
{
public VM()
{
OpenCommand = new RelayCommand(o => { });
}
public RelayCommand OpenCommand { get; set; }
}
这是主窗口构造器:
public MainWindow()
{
InitializeComponent();
DataContext = new VM();
peopleListBox.Items.Add(new object());
}
显然,您不能在用户控件内使用peopleListBox
。 它是在父控件中定义的字段,在子控件中不可访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.