【问题标题】:Get the item from list where the control pressed从按下控件的列表中获取项目
【发布时间】:2016-02-22 13:36:03
【问题描述】:

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

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>

我已将用户控件作为列表包含在我的主窗口中

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 类型的项目(发件人)。

【问题讨论】:

  • 我猜你将items绑定到ItemsControl,对吧?
  • @Zippy 是的。我已将Items 绑定到ItemsControl

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


【解决方案1】:

您必须为该button 设置CommandParameter

类似:

<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 中,您可以使用e.Parameter 访问它

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多