【问题标题】:WPF ItemsControl.ItemsTemplate Code BehindWPF ItemsControl.ItemsTemplate 代码后面
【发布时间】:2012-12-18 03:46:45
【问题描述】:

我目前正在使用绑定到 ViewModel 的 ItemsControl 模板来呈现对象集合。我有一个 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 中的特定对象并用它做一些事情,但我似乎无法弄清楚如何访问它(它是什么索引在集合中,等等)。

【问题讨论】:

  • 您需要对需要访问的对象做什么?我也不清楚你想要Data 项目还是Visual 项目。

标签: wpf itemscontrol


【解决方案1】:

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

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

当然,您必须将 yourItem 转换为您的项目类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 2018-11-24
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2022-01-20
    相关资源
    最近更新 更多