How should I edit WPF data that exists outside a C# task? I have defined a UI using the standard WPF template. The grid contains only:  &lt;TextBlock x:Name="myTextBox" Text="Original Text" /&gt;   In my code I have:  using System.Threading.Tasks; using System.Windows;  namespace UpdateGUI {   public partial class MainWindow : Window   {     private int myInt;      public MainWindow()     {       InitializeComponent();        myInt = 0;       Task.Factory.StartNew(() =&gt;       {         myInt++;         myTextBox.Text = "New Text";       });     }   } }   This throws the following exception:     The calling thread cannot access this object because a different thread owns it.   Which thread owns myTextBox?  Why don't I see this error when I edit myInt?
749
I have a scenario. (Windows Forms, C#, .NET)   There is a main form which hosts some user control. The user control does some heavy data operation, such that if I directly call the UserControl_Load method the UI become nonresponsive for the duration for load method execution. To overcome this I load data on different thread (trying to change existing code as little as I can)   I used a background worker thread which will be loading the data and when done will notify the application that it has done its work.   Now came a real problem. All the UI (main form and its child usercontrols) was created on the primary main thread. In the LOAD method of the usercontrol I'm fetching data based on the values of some control (like textbox) on userControl.    The pseudocode would look like this:  CODE 1  UserContrl1_LoadDataMethod() {     if (textbox1.text == "MyName") // This gives exception     {         //Load data corresponding to "MyName".         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage.     } }   The Exception it gave was     Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.   To know more about this I did some googling and a suggestion came up like using the following code  CODE 2  UserContrl1_LoadDataMethod() {     if (InvokeRequired) // Line #1     {         this.Invoke(new MethodInvoker(UserContrl1_LoadDataMethod));         return;     }      if (textbox1.text == "MyName") // Now it wont give an exception     {     //Load data correspondin to "MyName"         //Populate a globale variable List&lt;string&gt; which will be binded to grid at some later stage     } }   BUT BUT BUT... it seems I'm back to square one. The Application again  become nonresponsive. It seems to be due to the execution of line #1 if condition. The loading task is again done by the parent thread and not the third that I spawned.  I don't know whether I perceived this right or wrong. I'm new to threading.  How do I resolve this and also what is the effect of execution of Line#1 if block?  The situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.   So only accessing the value so that the corresponding data can be fetched from the database.
29507
I have been running  over some C# code, and it keeps reporting that my using directives should be inside the namespace.  Is there a technical reason for putting the using directives inside instead of outside the namespace?
81715
Edit:  Of course my real code doesn't look exactly like this. I tried to write semi-pseudo code to make it more clear of whay I wanted to do.  Looks like it just messed things up instead.  So, what I actually would like to do is this:  Method&lt;Interface1&gt;(); Method&lt;Interface2&gt;(); Method&lt;Interface3&gt;(); ...   Well ... I thought that maybe I could turn it into a loop using reflection. So the question is: How how do I do it. I have very shallow knowledge of reflection. So code examples would be great.  The scenario looks like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var i in interfaces)     {         Method&lt;i&gt;(); // Get compile error here!     }       Original post:  Hi!  I'm trying to loop through all interfaces in a namespace and send them as arguments to a generic method like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var interface in interfaces)     {         Method&lt;interface&gt;(); // Get compile error here!     } }   The error I get is "Type name expected, but local variable name found". If I try  ...     foreach(var interface in interfaces)     {         Method&lt;interface.MakeGenericType()&gt;(); // Still get compile error here!     } }   I get "Cannot apply operator '&lt;' to operands of type 'method group' and 'System.Type'" Any idea on how to get around this problem?
42034
First off, this is a question about a desktop application using Windows Forms, not an  question.  I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...  otherForm.Controls["nameOfControl"].Visible = false;   It doesn't work the way I would expect. I end up with an exception thrown from Main. However, if I make the controls public instead of private, I can then access them directly, as so...  otherForm.nameOfControl.Visible = false;   But is that the best way to do it? Is making the controls public on the other form considered "best practice"? Is there a "better" way to access controls on another form?  Further Explanation:  This is actually a sort of follow-up to another question I asked, . The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.  Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)
100125
The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().  public Boolean TryGetValue(TKey key, out TValue value) {     Boolean got = false;     WithReaderLock(delegate     {         got = dictionary.TryGetValue(key, out value);     });     return got; }   What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).
78162
I collect a few corner cases and  and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:  string x = new string(new char[0]); string y = new string(new char[0]); Console.WriteLine(object.ReferenceEquals(x, y));   I'd expect that to print False - after all, "new" (with a reference type) always creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should.  Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)  Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.  Any other gems lurking out there?
79121
My WPF application generates sets of data which may have a different number of columns each time.  Included in the output is a description of each column that will be used to apply formatting.  A simplified version of the output might be something like:  class Data {     IList&lt;ColumnDescription&gt; ColumnDescriptions { get; set; }     string[][] Rows { get; set; } }   This class is set as the DataContext on a WPF DataGrid but I actually create the columns programmatically:  for (int i = 0; i &lt; data.ColumnDescriptions.Count; i++) {     dataGrid.Columns.Add(new DataGridTextColumn     {         Header = data.ColumnDescriptions[i].Name,         Binding = new Binding(string.Format("[{0}]", i))     }); }   Is there any way to replace this code with data bindings in the XAML file instead?
5057
I have a child form that is throwing an ApplicationException in the Load event handler (intentionally for testing purposes).  The parent form wraps the ChildForm.Show() method in a Try...Catch ex As Exception block.  The catch block simply displays a message and closes the child form.  All works as expected when debugged in visual studio 2008 (.net 3.5 sp1).  However, when I run it outside of visual studio, the Catch block seems to get missed and an unhandled exception occurs.  Any idea why that is?  Thank you.  Example Code:  Public Class Form1      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click         Dim f2 As Form2          f2 = New Form2          Try             MessageBox.Show("Opening form 2")             f2.ShowDialog()         Catch ex As Exception             f2.Close()             MessageBox.Show("Form 2 closed.")         End Try     End Sub  End Class  Public Class Form2      Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load         Throw New ApplicationException("Test Form_Load")     End Sub      Public Sub New()          ' This call is required by the Windows Form Designer.         InitializeComponent()          ' Add any initialization after the InitializeComponent() call.     End Sub  End Class   Stack Trace:    System.ApplicationException:  Test Form_Load   at WindowsApplication1.Form2.Form2_Load(Object sender, EventArgs e)  in UnhandledExceptionTest2\WindowsApplication1\Form2.vb  System.Windows.Forms.Form.OnLoad(EventArgs e)  System.Windows.Forms.Form.OnCreateControl()  System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)  System.Windows.Forms.Control.CreateControl()  System.Windows.Forms.Control.WmShowWindow(Message& m)    at  System.Windows.Forms.Control.WndProc(Message&> m)    at  System.Windows.Forms.ScrollableControl.WndProc(Message&> m)    at  System.Windows.Forms.ContainerControl.WndProc(Message&> m)    at  System.Windows.Forms.Form.WmShowWindow(Message&> m)    at  System.Windows.Forms.Form.WndProc(Message&> m)    at  System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&> m)    at  System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&> m)    at  System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr  lparam)
20778
I have programmed with WPF for more than a year. When I started there weren't so many examples and guidelines to follow, now the situation is much more better.  I would like to ask you some help in listing the best WPF (open) source code examples or projects that you suggest to study in order to learn more about project structure, best practices, etc.  Thank you, Marco
95496
I have a 2-dimensional array of objects and I basically want to databind each one to a cell in a WPF grid.  Currently I have this working but I am doing most of it procedurally.  I create the correct number of row and column definitions, then I loop through the cells and create the controls and set up the correct bindings for each one.    At a minimum I would like to be able to use a template to specify the controls and bindings in xaml.  Ideally I would like to get rid of the procedural code and just do it all with databinding, but I'm not sure that's possible.  Here is the code I am currently using:  public void BindGrid() {     m_Grid.Children.Clear();     m_Grid.ColumnDefinitions.Clear();     m_Grid.RowDefinitions.Clear();      for (int x = 0; x &lt; MefGrid.Width; x++)     {         m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });     }      for (int y = 0; y &lt; MefGrid.Height; y++)     {         m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });     }      for (int x = 0; x &lt; MefGrid.Width; x++)     {         for (int y = 0; y &lt; MefGrid.Height; y++)         {             Cell cell = (Cell)MefGrid[x, y];                                  SolidColorBrush brush = new SolidColorBrush();              var binding = new Binding("On");             binding.Converter = new BoolColorConverter();             binding.Mode = BindingMode.OneWay;              BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);              var rect = new Rectangle();             rect.DataContext = cell;             rect.Fill = brush;             rect.SetValue(Grid.RowProperty, y);             rect.SetValue(Grid.ColumnProperty, x);             m_Grid.Children.Add(rect);         }     }  }
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
105022
I've been a .NET developer for several years now and this is still one of those things I don't know how to do properly. It's easy to hide a window from the taskbar via a property in both Windows Forms and WPF, but as far as I can tell, this doesn't guarantee (or necessarily even affect) it being hidden from the Alt+↹Tab dialog. I've seen invisible windows show up in Alt+↹Tab, and I'm just wondering what is the best way to guarantee a window will never appear (visible or not) in the Alt+↹Tab dialog.  Update: Please see my posted solution below. I'm not allowed to mark my own answers as the solution, but so far it's the only one that works.  Update 2: There's now a proper solution by Franci Penov that looks pretty good, but haven't tried it out myself. Involves some Win32, but avoids the lame creation of off-screen windows.
3920
Using C# and WPF under .NET (rather than  or console), what is the correct way to create an application that can only be run as a single instance?  I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.  The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
2033
I am working on a third party database.  When I try to view the definition of a view by right clicking, CREATE TO and then to NEW QUERY EDIT WINDOW, I am getting an error:     This property may not exist for this object or may not be retrievable   due to insufficient access rights. The text is encrypted.
110147
Since there's no button.PerformClick() method in WPF, is there a way to click a WPF button programmatically?
50142
I have a windows forms application with controls like textbox, combobox, datagridview etc. These controls allow a user to use the clipboad, i.e. cut/copy and paste text. It is also possible to delete text (which is not related to the clipboard).  My application has a menubar with an Edit item containing Cut/Copy/Paste/Delete items, and a toolbar with these items as well. How can I enable/disable these items properly depending in the state of the control having the focus?  I am looking for a generic way, i.e. I look for an implementation I do once, and can reuse for the future independent of the controls my application will use.
76874
In Windows Forms, I'd just override WndProc, and start handling messages as they came in.  Can someone show me an example of how to achieve the same thing in WPF?