Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

How to solve error - System.InvalidOperationException: 'The calling thread must be STA, because many UI components require this.'

$
0
0

HI,

I am facing error with the wpf application that I am working on, basically I would need the colour of the ellipse to change if the string contains OFF, please see my code. I do not understand this threading and have been reading of STAthread and placing it in the program, but I do not know where to place it. 

<Window x:Name="Testa" 
    x:Class="HelloWorld.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Hello" Width="1000" Height="700" Visibility="Visible" WindowStyle="SingleBorderWindow" WindowStartupLocation="CenterScreen"><Grid Name ="testgrid" ShowGridLines="False" Height="700" HorizontalAlignment="Center" VerticalAlignment="Center" Width="1000" ><Grid.ColumnDefinitions><ColumnDefinition Width="500" /><ColumnDefinition Width="500" /></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="100" /><RowDefinition Height="540" /><RowDefinition Height="10" /><RowDefinition Height="50" /></Grid.RowDefinitions><Border Grid.Row="0" Grid.Column="0" Background="#FF00144F" BorderBrush="#FF060E9F"/><Border Grid.Row="0" Grid.Column="1"><Image Source="Images\GD_backvisual.png" Stretch="UniformToFill"/></Border><Ellipse Grid.Column="1" Grid.Row="1" Fill="#FFC62F1A" Width="350" Height="350" x:Name="Stop_btn" VerticalAlignment="Center" HorizontalAlignment="Center"/><Button x:Name="btn_stop" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" Content="STOP" Width="100" Height="100" Click="button_stopClick" Background="#FFC62F1A" BorderBrush="#FFC62F1A"/><Image Grid.Row="0" Grid.Column="0" Source = "Images\GD_Logo_CT_neg_oSZ.png" Width="412" Height="400" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="26,-310,0,10"/><StackPanel Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"><ListBox Name="lbTodoList" HorizontalContentAlignment="Stretch" SelectionChanged="Test"><ListBox.ItemTemplate><DataTemplate><Grid Margin="50,2"><Grid.ColumnDefinitions><ColumnDefinition Width="50" /><ColumnDefinition Width="50" /></Grid.ColumnDefinitions><TextBlock Text="{Binding Title}" /><ProgressBar Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Completion}" /></Grid></DataTemplate></ListBox.ItemTemplate></ListBox></StackPanel><Label VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Column="0" Grid.Row="1" Name="TextLogged" Content="You are logged in as" FontFamily="Arial" FontSize="14" FontWeight="Bold" Margin="80,0,274,10"/><Label VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Column="0" Grid.Row="1" Name="Userlogged" Content="User" FontFamily="Arial" FontSize="14" FontWeight="Bold" Margin="226,0,16,10" Initialized="LabelTest" Width="258" BorderBrush="Black" BorderThickness="1" Background="#FF9AC8E1"/><Border Grid.Row="3" Grid.ColumnSpan="2" BorderBrush="#FF060E9F"><TextBlock Text="© 2019 Giesecke+Devrient Currency Technology Sdn Bhd (Malaysia). All rights reserved." FontFamily="Frutiger" VerticalAlignment="Top" HorizontalAlignment="Center" Height="25" Margin="261,10,278,0" Foreground="White" /><Border.Background><ImageBrush ImageSource="Images\GD_backvisual.png" /></Border.Background></Border></Grid><!--<Grid Name ="topTriangle" ><Polygon Name="triangle_top" Points="0,0 130,0, 130,130" Stroke="Black" Fill="Red"/><TextBlock Name="text_top"  Margin="82,20,20,76" FontSize="25" Text="55" Foreground="Black" /></Grid>--></Window>

C#

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IMLtools;
using System.IO;
using System.Timers;



namespace HelloWorld
{
    //    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    //public partial class MainWindow : Window
    //{
    //    //constructor - when we create the object, it will be called immediately
    //    public MainWindow()
    //    {
    //        InitializeComponent();
    //        //this.Title = "Main Window in Code Only";
    //        //this.Width = 700;
    //        //this.Height = 300;

    //    }
    //}
    
    //because we are actually creating the blueprint
    public partial class MainWindow : Window
    {
        

        private static System.Timers.Timer aTimer;
       
        public MainWindow()
        {
              
        InitializeComponent();

            //using (StreamReader sr = new StreamReader("C:/bps01_19100400.WLD"))
            //{

            //string store = sr.ReadToEnd();
            
            SetTimer();
           
           
            




            List<TodoItem> items = new List<TodoItem>();
            items.Add(new TodoItem() { Title = "Danny", Completion = 10 });
            items.Add(new TodoItem() { Title = "Chong", Completion = 80 });
            items.Add(new TodoItem() { Title = "Ning", Completion = 3 });

            lbTodoList.ItemsSource = items;

        }
        

        private static void SetTimer()
        {

            // Create a timer with a two second interval.
            aTimer = new Timer(1000);
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }


        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
          
        //MessageBox.Show("The Elapsed event was raised at {0:HH:mm:ss.fff}" + e.SignalTime);
        String last = File.ReadLines(@"C:/bps01_19100400.WLD").Last();
            //MessageBox.Show("Reading for Sensor's Logger, the time now is" + last);
            if(last.Contains("OFF"))
            {
                //MessageBox.Show("Sensor Contains" + last);
                SolidColorBrush mySolidColorBrush = new SolidColorBrush();

                ////// Describes the brush's color using RGB values. 
                ////// Each value has a range of 0-255.
                mySolidColorBrush.Color = Color.FromArgb(0, 0, 0, 0);

                MainWindow mw = new MainWindow();

                mw.Stop_btn.Fill = mySolidColorBrush;
               



            }
            aTimer.Stop();
            aTimer.Dispose();
        }


        private void button_runClick(object sender, RoutedEventArgs e)
        {
            
            int x = 2 + 2;
            MessageBox.Show("You have clicked the button");
            MessageBox.Show(x.ToString());
        }

        private void button_stopClick(object sender, RoutedEventArgs e)
        {

            Window1 secondWindow = new Window1();
            secondWindow.Show();
            //secondWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
        }

        private void LabelTest(object sender, EventArgs e)
        {
            //Userlogged.Content = lbTodoList.SelectedItem.ToString();

        }

        private void Test(object sender, SelectionChangedEventArgs e)
        {
            string storeindex;

            storeindex = lbTodoList.SelectedIndex.ToString();
            
            
            //type casting
            TodoItem selItem = (TodoItem)lbTodoList.SelectedItem;
            Userlogged.Content = selItem.Title;
        }

    }

    public class TodoItem
    {
        public string Title { get; set; }
        public int Completion { get; set; }
    }



}
Appreciate if someone could point out what I am missing and advice me on the next steps.


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>