0

如何在带有 Usercontrol 的 Lisview 中使用 DelegateCommand?在我的 Listview 中,我这样使用它:

<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}"/>

和这个:

 <Button Content="Click" Command="{Binding Path=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>
4

1 回答 1

0

您不能peopleListBox在用户控件的 XAML 中使用。它是在父控件中定义的字段,在子控件中不可访问。

您提供的代码对我有用(列表视图模板按钮单击调用命令处理程序):

<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在用户控件内部使用。它是在父控件中定义的字段,在子控件中不可访问。

于 2013-10-05T14:05:06.630 回答