从列表中获取按下控件的项目

时间:2016-02-22 13:36:04

标签: c# wpf user-controls routed-commands

我已经创建了一个示例应用程序,如下所示。

UserControl1.xaml

<Grid Margin="0,0,-155,0">
    <Label Content="{Binding Username}" HorizontalAlignment="Left" Margin="23,23,0,0" VerticalAlignment="Top"/>
    <Button Content="Close this UC" HorizontalAlignment="Left" Margin="414,22,0,0" VerticalAlignment="Top" Width="119" Command="{Binding ButtonClicked}" />
    <ProgressBar HorizontalAlignment="Left" Value="{Binding Completion}" Height="10" Margin="204,23,0,0" VerticalAlignment="Top" Width="154"/>
</Grid>

我已将usercontrol作为列表包含在我的MainWindow

MainWindow.Xaml

<Grid>
    <ItemsControl x:Name="icTodoList">

        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type local:UserControl1}">

                <local:UserControl1 />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

Mainwindow.xaml.cs

    public partial class MainWindow : Window
    {
        ObservableCollection<TodoItem> items = new ObservableCollection<TodoItem>();
        public MainWindow()
        {
            InitializeComponent();


            RoutedCommand rc = new RoutedCommand();
            CommandBindings.Add(new CommandBinding(rc, Button_click));

            items.Add(new TodoItem() { Username = "Eric", Completion = 45, ButtonClicked = rc });
            items.Add(new TodoItem() { Username = "Maxwell", Completion = 80 });
            items.Add(new TodoItem() { Username = "Sarah", Completion = 60 });
            icTodoList.ItemsSource = items;
        }

        private void Button_click(object sender, ExecutedRoutedEventArgs e)
        {
            **//Need to get the Item where the event triggered**
        }
    }

    public class TodoItem
    {
        public string Username { get; set; }
        public int Completion { get; set; }
        public RoutedCommand ButtonClicked { get; set; }
    }

问题: Button_Click事件处理程序在按预期单击按钮时被触发。但是,我无法获得单击按钮的TodoItem类型的项目(发件人)。

1 个答案:

答案 0 :(得分:0)

您必须为// File : MyTableClass_Extend.cs public partial class MyTableClass { public TimeSpan Duration { get { TimeSpan ts =(TimeSpan) (EndDateTime - StartDateTime); return ts; } } } 设置CommandParameter

类似的东西:

button

您可以看到,作为参数,我设置了网格数据上下文(应该是<Button Content="Close this UC" HorizontalAlignment="Left" Margin="414,22,0,0" VerticalAlignment="Top" Width="119" Command="{Binding ButtonClicked}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Grid}}, Path=DataContext}"/> 类型的项目)

然后,在TodoItem中,您可以RoutedCommand

访问它