One Simple Question, accessing User Control properties with Roslyn.
Hey People!
I've being trying to do a simple thing (I guess), but I can't figure out how to do it. I have this Grid objectGrid inside a MainWindow (WPF C# VS 2015).
So, I'd like to know how I can change the properties of this objectGrid within a script with Roslyn. The code I have is below (I'm just trying to change the Width of this Grid):
using System; using System.Collections.Generic; 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 Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using System.Threading;
using System.Diagnostics;
namespace WpfApplication2 { public partial class MainWindow : Window { public Thread atualizadorScript;
public MainWindow()
{
InitializeComponent();
atualizadorScript = new Thread(() => atualizarGrid());
atualizadorScript.Start();
}
public class Globals
{
public Grid gridWithinWindow;
}
public void atualizarGrid()
{
while (true)
{
Thread.Sleep(30);
CSharpScript.RunAsync(@"
gridWithinWindow.Width = gridWithinWindow.Width + 0.1;
", ScriptOptions.Default, new Globals { gridWithinWindow = objectGrid});
}
}
}
}
So, I'm just trying to use a infinite while loop, to run this little piece of code with CSharpScript.RunAsync(,,,). The code actually runs, doesn't throw any exceptions, but, the Grid just stays still, doesn't change its Width at all.
Any help to solve this would be appreciated. Thanks,
Lucas.
I'm not expert on WPF but I think you have to manipulate your UI objects on the UI thread, not a background/thread-pool thread.
Try this instead. It should keep the code running asynchronously on the same thread that started the main window.
public MainWindow()
{
InitializeComponent();
var ignore = atualizarGridAsync();
}
public class Globals
{
public Grid gridWithinWindow;
}
public async Task atualizarGridAsync()
{
while (true)
{
await Task.Delay(30);
await CSharpScript.RunAsync(@"
gridWithinWindow.Width = gridWithinWindow.Width + 0.1;
", ScriptOptions.Default, new Globals { gridWithinWindow = objectGrid});
}
}
Thanks people for considering this issue. Actually, I've decided to use IronPython as the Scripting language already.