如何从 ItemsControl 的 Item 后面的代码访问 ItemsControl 的 ItemsSource 元素?
在我的主视图中,我有一个 ItemsControl,它绑定到对象集合:
<ItemsControl ItemsSource="{Binding Path=Concepts}"
ItemTemplate="{StaticResource ActivationLevelTemplate}"
/>
其中 ActivationLevelTemplate 只是另一个视图:
<DataTemplate x:Key="ActivationLevelTemplate">
<view:ConceptActivationView Height="50"/>
</DataTemplate>
在此视图中,有一个文本块,绑定到上述集合中的对象的属性。该属性已正确显示,现在我需要从视图后面的代码访问同一对象的其他属性。这看起来微不足道,但我无法让它发挥作用。
<TextBlock Text="{Binding Path=Name}"
HorizontalAlignment="Center"
/>
<d3:Plotter2D Name="Plotter"/>
我遇到的最好的东西是 ItemContainerGenerator
但它似乎不是所需要的。
In my main view I have an ItemsControl which is bound to a collection of objects:
<ItemsControl ItemsSource="{Binding Path=Concepts}"
ItemTemplate="{StaticResource ActivationLevelTemplate}"
/>
Where the ActivationLevelTemplate is just another view:
<DataTemplate x:Key="ActivationLevelTemplate">
<view:ConceptActivationView Height="50"/>
</DataTemplate>
In this view there is a text block, bound to a property of an object from the collection mentioned above. The property is displayed correctly, and now I need to access other properties of the same object from the view's code behind. It seems trivial but I could not get it working.
<TextBlock Text="{Binding Path=Name}"
HorizontalAlignment="Center"
/>
<d3:Plotter2D Name="Plotter"/>
The best thing I came across was ItemContainerGenerator
but it does not seem to be what is needed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
重要的是您尝试访问该对象的上下文。例如,如果您处理 DataTemplate 内的事件,您可以轻松地从发送者的 DataContext 获取对象(必须是 FrameworkElement),例如,如果我要处理按钮单击:
事实上,如果您的整个视图都在DataTemplate 也可以直接从 View 的 DataContext 获取对象。
What is important is the context in which you try to access that object. If you for example deal with an event inside the DataTemplate you can easily get the object from the DataContext of the sender (has to be a FrameworkElement), e.g. if i were to handle a button click:
In fact if your whole view is inside the DataTemplate you can get the object directly from the View's DataContext as well.
您应该能够迭代 ItemsControl 中的项目并获取所需的所有属性。为 ItemsControl 指定一个名称,以便您可以在后面的代码中对其进行寻址:
然后在后面的代码中
如果您需要特定的项目,您可以尝试 CurrentItem 或 GetItemAt()
You should be able to iterate through the items in the ItemsControl and get all the properties you need. Give the ItemsControl a name so you can address it in the code behind:
Then in code behind
If you need a specific item you could try CurrentItem or GetItemAt() instead