【问题标题】:DelegateCommand in Listview with UserControlListview 中的 DelegateCommand 与 UserControl
【发布时间】:2013-10-05 13:37:10
【问题描述】:

如何在我的 Lisview 中通过 Usercontrol 使用 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
    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>

【问题讨论】:

  • 为什么要在DataTemplate 中使用具有相同命令的按钮?该模板适用于所有项目。你想一遍又一遍地用相同的命令使用相同的按钮吗?
  • 你能提供UserControl的代码吗?
  • 这只是一个示例,展示了我如何在列表视图中使用带有命令的按钮(不在用户控件中)
  • @meilke,这是我的代码

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


【解决方案1】:

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

【讨论】:

  • 当我将按钮放在 Listview 中时,我的代码工作正常。我不能在我的UserControl 中使用按钮绑定
  • 检查我答案的底部。
猜你喜欢
  • 2016-05-13
  • 1970-01-01
  • 2013-06-04
  • 2016-06-16
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多