2012-12-17 63 views
1

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

下面是我在的地方代码:

<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中特定的对象,并做一些东西吧,但我似乎无法弄清楚如何访问它(它在集合中的索引等)。

+0

你需要怎么处理你需要访问的对象?我也不清楚你是否想要“数据”项目或“视觉”项目。 –

回答

3

你会发现你的特定对象在发送DataContext

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

当然,你要投yourItem你的项目类。