我当前正在使用绑定到 ViewModel 的 ItemsControl 模板来呈现对象的集合。 我有一个切换按钮作为模板的一部分。 我想在代码隐藏中访问绑定到集合中该 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 中的该特定对象并对其进行一些操作,但我似乎无法弄清楚如何访问它(它在集合中的索引等)。
您将在发件人的DataContext
中找到您的特定对象:
private void OnProfileToggle(object sender, MouseButtonEventArgs e)
{
ToggleButton button = sender as ToggleButton;
object yourItem = button.DataContext;
}
当然,你必须将你的项目强制转换为你的项目类。