Answer the question
In order to leave comments, you need to log in
How in ItemsControl to execute the method of the source class when an event occurs (for example, a mouse click)?
Hello. I don’t know what exactly those who try to help me may need, so I don’t post the code so as not to confuse anyone. I will describe the essence of the problem on apples.
There is a class
field1
field2
***
Method1(parameter)
There is also a form on which the ItemsControl is located, which displays a collection (sheet) of instances of this class and includes a DataTemplate for instances. This is a Border, inside which is a TextBlock that displays, for example, field1.ToString(). And I still need Method1 (with a parameter) to be executed by pressing the left mouse button. When adding the PreviewMouseLeftButtonDown event to the ItemsControl itself, I get a collection of instances as a sender, and when I add an event to the Border, I get a Border :)
And when I click on an element, I need to get an instance of the class on the basis of which it was drawn in order to execute Instance.Method1 (with a parameter). Well, I don’t hope to transfer the parameter from XAML (but I would like to), but there should be a way to get the instance itself. How? Thank you.
Well, you can, of course, specify Tag = "{Binding}" in the Border, but I would not want to. I always leave the tag for temporary crutches, so it's not worth borrowing.
Answer the question
In order to leave comments, you need to log in
As I understand it, since Method1 is in your viewmodel, then it has business logic (and not presentation logic). If so, then I advise you to turn it all through Command:
1) in the parent viewmodel (the one with the list) make a command with one parameter (in the example: DoStrangeThingCommand);
2) with the help of EventTrigger you make it so that on the event of pressing the l.k.m. this command twitched on the text block;
3) as a command parameter, we pass the current binding (that is, the selected element in the list);
4) in the team we actually pull Method1
5) profit
<DataTemplate ... >
<TextBlock>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}},
Path=DataContext.DoStrangeThingCommand}"
CommandParameter="{Binding}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question