C# 在具有UserControl的Listview中使用DelegateCommand
如何在Lisview和Usercontrol中使用DelegateCommand?在我的Listview中,我是这样使用它的:C# 在具有UserControl的Listview中使用DelegateCommand,c#,xaml,listview,user-controls,windows-store-apps,C#,Xaml,Listview,User Controls,Windows Store Apps,如何在Lisview和Usercontrol中使用DelegateCommand?在我的Listview中,我是这样使用它的: <ListView x:Name="peopleListBox"> <ListView.ItemTemplate> <DataTemplate> <Grid> &
<ListView x:Name="peopleListBox">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<UserControls:ItemTemplateControl QuestionText="{Binding parametr}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView>
我正在用户控件中尝试:
<Button Content="Click" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/>
<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>
这是:
<Button Content="Click" Command="{Binding Path=OpenCommand, ElementName=peopleListBox}"/>
这两种代码都不起作用
用户控制:
<Button Content="Click" Command="{Binding Path=DataContext.OpenCommand, ElementName=peopleListBox}"/>
<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
。它是在父控件中定义的字段,在子控件中不可访问
您提供的代码适用于我(列表视图模板按钮单击调用命令处理程序):
以下是主窗口构造函数:
public MainWindow()
{
InitializeComponent();
DataContext = new VM();
peopleListBox.Items.Add(new object());
}
显然,您不能在用户控件内使用
peopleListBox
。它是在父控件中定义的字段,在子控件中不可访问。为什么要在数据模板中使用具有相同命令的按钮?该模板适用于所有项目。你想一次又一次地用同一个命令使用同一个按钮吗?你能提供UserControl
的代码吗?这只是一个示例,演示了如何在listview(而不是UserControl)中使用带有命令的按钮@meilke,这是我的代码当我将按钮放在listview中时,我的代码工作正常。我不能在我的UserControl
中使用绑定,因为我的答案的底部是臀部。