WPF ItemsControl.ItemTemplate代码背后

时间:2012-12-17 19:26:28

标签: wpf itemscontrol

我目前正在使用ItemsControl模板绑定到ViewModel以呈现对象集合。我有一个ToggleButton作为模板的一部分。我想在后面的代码中访问绑定到集合中的UI项的对象。

以下是我的代码:

<ItemsControl.ItemTemplate>
   <DataTemplate>
      <StackPanel HorizontalAlignment="Stretch" Orientation="Horizontal">
           <ToggleButton Cursor="Hand"
                         IsChecked="{Binding IsActive, Mode=TwoWay}"
                         IsEnabled="{Binding CanToggleOnProfile}"
                         Style="{StaticResource ProfileToggleButtonStyle}" 
                         PreviewMouseLeftButtonUp="OnProfileToggle">

我想在OnProfileToggle调用后面的代码中,访问DataTemplate中的特定对象并用它做一些事情,但我似乎无法弄清楚如何访问它(什么索引)它在集合中等。)

1 个答案:

答案 0 :(得分:3)

您会在发件人DataContext中找到您的特定对象:

private void OnProfileToggle(object sender, MouseButtonEventArgs e)
{
    ToggleButton button = sender as ToggleButton;
    object yourItem = button.DataContext;
}

当然,您必须将 yourItem 投射到您的项目类。

相关问题