Sunday, January 25, 2009

Silverlight: Event Bubbling

Nézzünk egy egyszerű példát:
Egy StackPanel-be teszünk egy StackPanel-t, és abba egy Rectanglét. Mind a három controlra rákötjük a MouseLeftButtonDown="Button_MouseLeftButtonDown" eseményt (ugyanazt).
Vajon mi fog történni? Igen alapból háromszor hívódik meg az esemény...


private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)


        {


            int szamol = Convert.ToInt32(Szamol.Text) + 1;


            Szamol.Text = szamol.ToString();


            //e.Handled = true;


        }




Persze ezt el is tudjuk kerülni, elég a e.Handled -et true-ra állítani.

"Bubbling events are events that travel up the containment hierarchy. For
example, MouseLeftButtonDown is a bubbling event. It’s raised first by the
element that is clicked. Next, it’s raised by that element’s parent, and then
by that element’s parent, and so on, until Silverlight reaches the top of the
element tree."

"Bubbling events allow you to do two useful things:
-Centralize event handling logic: For example, you may have a layout panel
full of Image elements. When an image is clicked, you want to display some
information about it in another part of your user interface. Rather than
connect each Image element to the same event handler that does the work, you
could attach the event handler once, at the container level.
-Deal with content controls: Certain controls have the ability to hold virtually
other elements. One example is the Button class, which can hold a piece of
text or a layout panel that might contain a combination of text, shapes, and
images. In order to react to button clicks, the button needs to be able to
intercept mouse actions that happen to any of its contained elements."

Silverlight: Dependency property

Hogy tudjuk kódból állítani a különböző paramétereket(dependency): ugye a Buttonnak alapból nincs Grid tulajdonsága, tehát itt ezt nem tudjuk elérni..


    1 private void Button_Click(object sender, RoutedEventArgs e)


    2         {


    3             int oszlop = (int)Gomb.GetValue(Grid.ColumnProperty);


    4             int sor = (int)Gomb.GetValue(Grid.RowProperty);


    5             if (oszlop < 3)


    6             {


    7                 oszlop++;


    8             }


    9             else if (sor < 3)


   10             {


   11                 sor++;


   12                 oszlop = 0;


   13             }


   14             else


   15             {


   16                 oszlop = 0;


   17                 sor = 0;


   18             }


   19             Grid.SetColumn(Gomb, oszlop);


   20             Grid.SetRow(Gomb, sor);


   21         }




Demó alkalmazás