invalidoperationexception In the Begin method of Save The Humans Game - c#

I started learning C# using the book Head First C# and i'm doing the game in chapter 1 using WPF project , the thing is i think i followed everything according to the book but i get a invalidoperationexception in the begin method
here is the code i wrote :
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 System.Windows.Media.Animation;`
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Random random = new Random();
public MainWindow()
{
InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
AddEnemy();
}
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy,0,Play_Area.ActualWidth-100,"(Canvas.left)");
AnimateEnemy(enemy, random.Next((int)Play_Area.ActualHeight - 100), random.Next((int)Play_Area.ActualHeight - 100), "(Canvas.Top)");
Play_Area.Children.Add(enemy);
}
private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
{
Storyboard storyboard = new Storyboard () { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
DoubleAnimation animation = new DoubleAnimation()
{
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6))),
};
Storyboard.SetTarget(animation, enemy);
Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));
storyboard.Children.Add(animation);
storyboard.Begin();
}
}
}
Here is a picture of my document Outline : Document Outline
why do i get the exception ? can anyone help me ?

Property names are case-sensitive. Try to change Canvas.left to Canvas.Left with an upper-case L:
AnimateEnemy(enemy,0,Play_Area.ActualWidth-100,"(Canvas.Left)");

Related

Are there any flags i need to provide to CefSharp to work with document elements?

I converted a window of mine to use CefSharp in order to render some PDF file. One of the features the old component supported (WebBrowser of WPF, which unfortunately depends on IE, which does not work in this case) is accessing javascript elements through code in order to be aware of when the PDF has been scrolled to the bottom. Unfortunately this does not appear to work with CefSharp with the following code. Perhaps i am missing some initializer flag for this to work?
Currently in my Logs All i get is ScrollProgress|0|0|734
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.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CefSharp;
using NLog;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using WebBrowser = System.Windows.Forms.WebBrowser;
namespace MyNamespace
{
public partial class PdfConfirmWindow : Window
{
private static readonly ILogger Log = LogManager.GetLogger(nameof(PdfConfirmWindow));
public PdfConfirmWindow()
{
InitializeComponent();
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
ChromiumWebBrowser.LoadingStateChanged += ChromiumWebBrowserOnLoadingStateChanged;
UpdateBrowserContent();
}
private void ChromiumWebBrowserOnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (!e.IsLoading)
{
Log.Debug("Loading completed");
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// (window.innerHeight + window.scrollY) >= document.body.offsetHeight
// e.scrollHeight - e.scrollTop === e.clientHeight
// CefSharp.PostMessage('EndOfDocumentReached');
const string script = #"
(function(){
var intervalHandler;
function onScrollCallback() {
var e = document.body;
var values = ['ScrollProgress'];
values.push(document.body.clientHeight);
values.push(window.scrollY);
values.push(window.innerHeight);
CefSharp.PostMessage(values.join('|'));
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
//clearInterval(intervalHandler);
}
}
setTimeout(function(){
var intervalHandler = setInterval(function(){
onScrollCallback();
}, 100);
}, 500);
})();
";
ChromiumWebBrowser.Focus();
ChromiumWebBrowser.WebBrowser.JavascriptMessageReceived += WebBrowserOnJavascriptMessageReceived;
ChromiumWebBrowser.WebBrowser.ExecuteScriptAsync(script);
}));
}
}
private async void WebBrowserOnJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
await UIHelper.Thread;
// ChromiumWebBrowser.WebBrowser.JavascriptMessageReceived -= WebBrowserOnJavascriptMessageReceived;
if (e.Message?.ToString().Equals("EndOfDocumentReached", StringComparison.OrdinalIgnoreCase) == true)
{
SetReachedStatus(true);
}
if (e.Message?.ToString().StartsWith("ScrollProgress", StringComparison.OrdinalIgnoreCase) == true)
{
Log.Debug(e.Message?.ToString());
}
}
}

Can't get to animate the margin top in WPF

I have a StackPanel named MainStack. I am trying to move the stackpanel vertically down by animating its margin top property using ThicknessAnimation . I honestly have no Idea why my code is not doing anything. any help would be appreciated.
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 System.Windows.Media.Animation;
namespace casino
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ThicknessAnimation myThicknessAnimation = new ThicknessAnimation();
myThicknessAnimation.Duration = TimeSpan.FromSeconds(5);
myThicknessAnimation.FillBehavior = FillBehavior.HoldEnd;
myThicknessAnimation.From = new Thickness(20, 20, 0, 0);
myThicknessAnimation.To = new Thickness(20, 200, 0, 0);
Storyboard.SetTargetName(myThicknessAnimation, "MainStack");
Storyboard.SetTargetProperty(
myThicknessAnimation, new
PropertyPath(Border.BorderThicknessProperty));
Storyboard ellipseStoryboard = new Storyboard();
ellipseStoryboard.Children.Add(myThicknessAnimation);
}
}
}

C# "Controls" Does Not Exist in The Current Context

Error
In my application I'm trying to use "Controls.Add", but Visual Studio keeps giving me the error:
"Error 1 The name 'Controls' does not exist in the current context
C:\Users\Admin\Desktop\Demo\Demo\MainWindow.xaml.cs 42 13 Demo"
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;
namespace Demo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 window = new Window1();
Button button = new Button();
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
button.Content = "New Button";
button.Visibility = Visibility.Visible;
button.Height = 50;
button.Width = 200;
Controls.add(button); <-- ERROR IS FOUND HERE
window.Show();
}
}
}
I'm using WPF, coming from WinForms. Any advice is appreciated, thanks.
You need to do something along the lines of:
var window = new Window1();
var stackPanel = new StackPanel { Orientation = Orientation.Vertical };
Button button = new Button();
button.Content = "New Button";
button.Visibility = Visibility.Visible;
button.Height = 50;
button.Width = 200;
stackPanel.Children.Add(button);
window.Content = stackPanel;
window.Show();
Although, I'd recommend defining all UI components in the XAML and reading up on the MVVM pattern.
<StackPanel Name=“splMain“>
<Button Name=“btnAddMore“ Click=“btnAddMore_Click“>Add Another</Button>
Also on button click :
System.Windows.Controls.Button newBtn = new Button();
newBtn.Content = “A New Button”;
splMain.Children.Add(newBtn);
Button SaveButton = new Button();
SaveButton.Name = "Save";
SaveButton.Content = "Save";
Grid1.Children.Add(SaveButton);

Label wont trigger in if statement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Hi this WPF alarm app wont trigger the label to be fed in via animation. Initially it was made in a Form then I brought into WPF. When in C# Form this was all fine, everything triggered, but as soon as I brought it into WPF it wouldn't trigger.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Dynamic;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Web;
using System.Timers;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Diagnostics;
using System.Windows.Media.Animation;
namespace Alarm_Clock_WPF
{
public partial class MainWindow : Window
{
DispatcherTimer dispatcherTimer1 = new DispatcherTimer();
DispatcherTimer dispatcherTimer2 = new DispatcherTimer();
public MainWindow()
{
System.Windows.Threading.DispatcherTimer dispathcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer1.Tick += new EventHandler(dispatcherTimer1_Tick);
dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
dispatcherTimer1.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer1.Start();
dispatcherTimer2.Start();
InitializeComponent();
}
private void dispatcherTimer1_Tick(object sender, EventArgs e)
{
CountTime.Content = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00");
if (CountTime.Content == TriggerTime.Content)
{
DateTime now2 = DateTime.Now;
string date1 = DateTime.Today.ToString("D");
string time2 = now2.GetDateTimeFormats('t')[0];
//Label Leave Animation
//DoubleAnimation animation = new DoubleAnimation(0, TimeSpan.FromSeconds(2));
//label4.BeginAnimation(OpacityProperty, animation);
System.Diagnostics.Process.Start("https://www.youtube.com/");
//Music
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(#"C:\Users\*****\Documents\Wake up theme 01.wav");
sp.Play();
//Video
//Video beach = new Video(#"C:\Users\******\Desktop\Jarvis\...avi");
//beach.Play();
label1.Content = "Done";
//Actual Wake Up Call
dispatcherTimer1.Stop();
}
}
private void dispatcherTimer2_Tick(object sender, EventArgs e)
{
//Alarm settings
if (CountTime.Content == TriggerTime.Content)
{
DateTime now2 = DateTime.Now;
string date1 = DateTime.Today.ToString("D");
string time2 = now2.GetDateTimeFormats('t')[0];
//Label Leave Animation
//DoubleAnimation animation = new DoubleAnimation(0, TimeSpan.FromSeconds(2));
//label4.BeginAnimation(OpacityProperty, animation);
System.Diagnostics.Process.Start("https://www.youtube.com/");
//Music
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(#"C:\Users\*******\Documents\Wake up theme 01.wav");
sp.Play();
//Video
//Video beach = new Video(#"C:\Users\*******\Desktop\Jarvis\...avi");
//beach.Play();
label1.Content = "Done";
//Actual Wake Up Call
dispatcherTimer1.Stop();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
TriggerTime.Content = DateTime.Today.Hour.ToString("00") + ":" + DateTime.Today.Minute.ToString("00") + ":" + DateTime.Today.Second.ToString("00");
}
}
}
Obviously the coding itself is pretty bad, but the reason im here is to find out why the the 2 labels "CountTime and TriggerTime" wont trigger, if I set them != they trigger automatically. But when set == they dont.
To sum up comments. Because Content is an Object you compare it by reference. Use Equals method, which is overridden by String, to compare values:
CountTime.Content.Equals(TriggerTime.Content)
or cast both values to String and then compare them:
(string)CountTime.Content == (string)TriggerTime.Content

Grid Lines wont show

Grid lines wont show on runt-time I can seem to see where I am going wrong. This is a WPF window application. I just want to generate columns and rows using C# code. Any ideas why this is not working?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
namespace generator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CreateGrid()
{
ColumnDefinition myColum =new ColumnDefinition();
RowDefinition myRow = new RowDefinition();
ColumnDefinition myColum1 = new ColumnDefinition();
RowDefinition myRow1 = new RowDefinition();
Grid myGrid = new Grid();
myRow.Height = new GridLength(1, GridUnitType.Star);
myColum.Width = new GridLength(1, GridUnitType.Star);
myRow1.Height = new GridLength(1, GridUnitType.Star);
myColum1.Width = new GridLength(1, GridUnitType.Star);
myGrid.ColumnDefinitions.Add(myColum);
myGrid.RowDefinitions.Add(myRow);
myGrid.ColumnDefinitions.Add(myColum1);
myGrid.RowDefinitions.Add(myRow1);
myGrid.ShowGridLines = true;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
CreateGrid();
}
}
}
The question may as well read "Grid won't show".
You are creating a new Grid instance, but you never add it to the visual tree. You may assign it to the Window's Content property:
private void CreateGrid()
{
...
Content = myGrid;
}

Categories