【发布时间】: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