Reputation: 1169
I am developping a project in order to manipulate a lot of objects with several modalities (mouse, leapmotion, touch ...). I made it using the MVVM pattern soI have several Views and ViewModels for all the components I will use. To make it easier to develop I chose to have a Canvas component in which I will manipulate Grids. Each Grid can contain any type of object (Shape, Text, Image, Documents...).
To be able to have all modalities linked to my method, I decided to build one listener per modality (1 for the mouse, 1 for the leapmotion...) and make them detect basic gestures (as Click, DoubleClick ...). All the gestures I chose to detect are associate with a method via a Dictionary. Anyway the linking is working as expected as it executes the right method. T o give an example I have the action calling in my mouse listener:
if (_leftClickCounter == 1 && _capturedLeft == false)
{
if (_dic.ContainsKey(Key.OnClick))
{
Action<object> action = _dic[Key.OnClick];
action.Invoke(null);
}
}
Where:
In my example the method executed is:
public void Add(object sender)
{
ObjectModel objectModel = new ObjectModel();
ObjectView objectView = new ObjectView(objectModel);
this.objectViews.Add(objectView);
}
Where sender is just used for test purpose. It remains unused in the method. My execution stops when it tries to instanciate my ObjectView saying:
InvalidOperationException
The calling thread must be STA, because many UI components require this
My ObjectView.xaml.cs class is:
public partial class ObjectView : UserControl
{
public ObjectView(ObjectModel obj)
{
InitializeComponent();
EventLinker linker = new EventLinker(this.visualBox);
ObjectViewModel objectVM = new ObjectViewModel(obj, linker);
this.DataContext = objectVM;
}
}
And its ObjectView.xaml defining the UserControl to use is very basic:
<UserControl x:Class="AusyTouchMultimodal_v1.View.ObjectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid x:Name="visualBox" Background="Blue"/>
</UserControl>
I dont have any compilation errors, just this InvalidOperationException. Can someone explain this issue to me?
Thanks!
Upvotes: 1
Views: 452
Reputation: 305
Try calling your actions in ui thread, like this
if (_leftClickCounter == 1 && _capturedLeft == false)
{
if (_dic.ContainsKey(Key.OnClick))
{
Action<object> action = _dic[Key.OnClick];
// action.Invoke(null);
System.Windows.Application.Current.Dispatcher.BeginInvoke( call your action )
}
}
Upvotes: 2