使用UserControl在Listview中委托命令

时间:2013-10-05 13:37:11

标签: c# xaml listview user-controls windows-store-apps

如何在我的Lisview中使用DelegateCommand和Usercontrol?在我的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
    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>

1 个答案:

答案 0 :(得分:0)

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