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 Autolaskuri
{
///
/// Interaction logic for UserControl1.xaml
///
public partial class AutolaskuriControl : UserControl
{
private int paikka = 0;
private int laskuri = 0;
System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
public static RoutedCommand LisaaAutoCommand = new RoutedCommand();
public AutolaskuriControl()
{
InitializeComponent();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = new TimeSpan(0, 0, 0, 0, 20);
timer.Start();
CommandBinding OmaCommandBinding = new CommandBinding(
LisaaAutoCommand, LisaaAutoExecuted, LisaaAutoCanExecute);
CommandBindings.Add(OmaCommandBinding);
button1.Command = LisaaAutoCommand;
}
void LisaaAutoExecuted(object target, ExecutedRoutedEventArgs e)
{
laskuri++;
label1.Content = laskuri.ToString();
RoutedPropertyChangedEventArgs args = new RoutedPropertyChangedEventArgs(
laskuri-1, laskuri, LaskuriChangedEvent);
RaiseEvent(args);
}
void LisaaAutoCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// label1.Content = Canvas.GetLeft(auto).ToString();
if ( Canvas.GetLeft(auto) < this.ActualWidth)
e.CanExecute = true;
}
private void timer_Tick(object sender, EventArgs e)
{
// attached property pitää päivittää alkuperäisen luokan kautta
Canvas.SetLeft(auto, paikka);
paikka++;
if (paikka > 200) paikka = -50;
// ilman seuraavaa riviä komennon LisaaAutoCanExecutea ei suoriteta oikealla hetkellä
// ei ole kovin tehokas tämä ratkaisu...
CommandManager.InvalidateRequerySuggested();
}
// esitellään ja rekisteröidään event
public static readonly RoutedEvent LaskuriChangedEvent = EventManager.RegisterRoutedEvent(
"LaskuriChanged", // tapahtuman nimi
RoutingStrategy.Bubble, // toimintatapa
typeof(RoutedPropertyChangedEventHandler), //eventissä liikuteltavan tiedon tietotyyppi int
typeof(AutolaskuriControl)); // luokka johon event lisätään
public event RoutedPropertyChangedEventHandler LaskuriChanged
{
add { AddHandler(LaskuriChangedEvent, value); }
remove { RemoveHandler(LaskuriChangedEvent, value); }
}
private void UserControl_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
try
{
string txt = e.Data.GetData(DataFormats.Text) as string;
int luku = Convert.ToInt16(txt);
// seuraava pitäisi olla toteutettu propertyn avulla! Nyt hieman laiska cut-and-paste-versio, hyi
laskuri += luku;
label1.Content = laskuri.ToString();
RoutedPropertyChangedEventArgs args = new RoutedPropertyChangedEventArgs(
laskuri - luku, laskuri, LaskuriChangedEvent);
RaiseEvent(args);
}
catch (Exception)
{
return;
}
}
}
}
}