Archive

Posts Tagged ‘Code’

Daily Demo: Silverlight Fullscreen Trigger Action

March 19th, 2010

A common needed and used feature in Silverlight is the Fullscreen Mode. A feature to switch the current application from a hosted in browser to fullscreen mode. This features is interesting in scenarios like Point of Sales- or Games-Applications.

image

Normal Browser Mode

image

Full Screen Mode

Livepreview here

XAML-Code

<UserControl x:Class="FullScreenBehavior.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:TheOliver_Controls="clr-namespace:TheOliver.Controls"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Button
            Content="Button"
            Height="23"
            HorizontalAlignment="Left"
            Margin="10,10,0,0"
            Name="button1"
            VerticalAlignment="Top"
            Width="75">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <TheOliver_Controls:FullScreenAction/>
                </i:EventTrigger>
            </i:Interaction.Triggers>

        </Button>
        <Rectangle Stroke="Black" Margin="155,113,141,110">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonUp">
                    <TheOliver_Controls:FullScreenAction/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="White" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</UserControl>

Sourcecode

// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows;
using System.Windows.Interactivity;

namespace TheOliver.Controls
{
    public class FullScreenAction : TargetedTriggerAction<FrameworkElement>
    {
        protected override void Invoke(object o)
        {
            Application.Current.Host.Content.IsFullScreen =
                !Application.Current.Host.Content.IsFullScreen;
        }

    }
}

 

Solution download

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

English, Expression, Silverlight, Visual Studio

Daily Demo: Silverlight Behavior for 3D Hover Effect

March 18th, 2010

Behaviors are great new feature in Silverlight 3 (or better in Blend 3) for adding “features” to a control without coding. My favorite sample is a hover effect, that applies when a mouse enters a control.

 

image

 

Live-Preview

 

XAML-Code:

 

<UserControl
    x:Class="Hover3DBehavior.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:TheOliver_Controls="clr-namespace:TheOliver.Controls"
    d:DesignHeight="300"
    d:DesignWidth="400"
    xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input">

    <Grid
        x:Name="LayoutRoot"
        Background="White">
        <Button
            Content="Button"
            Height="23"
            HorizontalAlignment="Left"
            Margin="89,78,0,0"
            Name="button1"
            VerticalAlignment="Top"
            Width="75">
            <i:Interaction.Behaviors>
                <TheOliver_Controls:Hover3DBehavior />
            </i:Interaction.Behaviors>
        </Button>

        <dataInput:Label
            Height="50"
            HorizontalAlignment="Left"
            Margin="274,64,0,0"
            Name="label1"
            VerticalAlignment="Top"
            Width="100"
            Content="Hello World">
            <i:Interaction.Behaviors>
                <TheOliver_Controls:Hover3DBehavior />
            </i:Interaction.Behaviors>
        </dataInput:Label>

        <RadioButton
            Content="RadioButton"
            Height="16"
            HorizontalAlignment="Left"
            Margin="12,133,0,0"
            Name="radioButton1"
            VerticalAlignment="Top">
            <i:Interaction.Behaviors>
                <TheOliver_Controls:Hover3DBehavior />
            </i:Interaction.Behaviors>
        </RadioButton>

    </Grid>
</UserControl>

 

Source-Code:

 

// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace TheOliver.Controls
{
    public class Hover3DBehavior : Behavior<UIElement>
    {
        PlaneProjection _planeProjection;

        public Hover3DBehavior()
            : base()
        {

        }

        Storyboard _hoverMe;
        Storyboard _unhoverMe;

        public double ZHoverValue
        {
            get { return (double)GetValue(ZHoverValueProperty); }
            set { SetValue(ZHoverValueProperty, value); }
        }

        public static readonly DependencyProperty ZHoverValueProperty =
            DependencyProperty.Register("ZHoverValue", typeof(double), typeof(Hover3DBehavior),
            new PropertyMetadata(500.0, null));

        public int HoverDurationMilliseconds
        {
            get { return (int)GetValue(HoverDurationMillisecondsProperty); }
            set { SetValue(HoverDurationMillisecondsProperty, value); }
        }

        public static readonly DependencyProperty HoverDurationMillisecondsProperty =
            DependencyProperty.Register("HoverDurationMilliseconds"
            , typeof(int)
                , typeof(Hover3DBehavior),
                new PropertyMetadata(200, null));

        #region Overrides 

        protected override void OnAttached()
        {
            base.OnAttached();

            _planeProjection = new PlaneProjection();
            this.AssociatedObject.Projection = _planeProjection;

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                _hoverMe = new Storyboard();

                DoubleAnimation da1 = new DoubleAnimation();

                _hoverMe.Children.Add(da1);
                da1.Duration = new Duration(new System.TimeSpan(0, 0, 0, 0, HoverDurationMilliseconds));
                da1.To = this.ZHoverValue;
                Storyboard.SetTarget(da1, this.AssociatedObject);
                Storyboard.SetTargetProperty(da1, new PropertyPath("(UIElement.Projection).(PlaneProjection.LocalOffsetZ)"));

                DoubleAnimation da2 = new DoubleAnimation();
                BounceEase be2 = new BounceEase();
                be2.EasingMode = EasingMode.EaseOut;
                be2.Bounces = 3;
                da2.EasingFunction = be2;

                _unhoverMe = new Storyboard();
                _unhoverMe.Children.Add(da2);
                da2.Duration = new Duration(new System.TimeSpan(0, 0, 0, 0, 1000));
                da2.To = 0.0;
                Storyboard.SetTarget(da2, this.AssociatedObject);
                Storyboard.SetTargetProperty(da2, new PropertyPath("(UIElement.Projection).(PlaneProjection.LocalOffsetZ)"));

                if ((this.AssociatedObject as FrameworkElement).Resources.Contains("hoverme"))
                {
                    (this.AssociatedObject as FrameworkElement).Resources.Remove("hoverme");
                }
                (this.AssociatedObject as FrameworkElement).Resources.Add("hoverme", _hoverMe);

                if ((this.AssociatedObject as FrameworkElement).Resources.Contains("unhoverme"))
                {
                    (this.AssociatedObject as FrameworkElement).Resources.Remove("unhoverme");
                }
                (this.AssociatedObject as FrameworkElement).Resources.Add("unhoverme", _unhoverMe);
            }

            this.AssociatedObject.MouseEnter += AssociatedObject_MouseEnter;
            this.AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;

        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            this.AssociatedObject.Projection = null;
            _planeProjection = null;

            this.AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
            this.AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
        }

        #endregion

        #region Events

        void AssociatedObject_MouseLeave(object sender, MouseEventArgs e)
        {
            _unhoverMe.Begin();
        }

        void AssociatedObject_MouseEnter(object sender, MouseEventArgs e)
        {
            //FrameworkElement e1 = this.AssociatedObject as FrameworkElement;
            //if (e1.Parent is Panel)
            //{
            //    Panel p = e1.Parent as Panel;
            //    if (p != null)
            //    {
            //        UIElement element = this.AssociatedObject;
            //        element.SetValue(UIElement.
            //        p.Children.Remove(element);
            //        p.Children.Add(element);
            //    }
            //}
            _hoverMe.Begin();
        }

        #endregion

    }
}

 

Download-SampleCode

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, English, Expression, Silverlight, Visual Studio

Daily Demo: Silverlight Image Stack

March 17th, 2010

An interesting control is a Image Stack, where Images are stacked on top of each other. Normally you remove the image on top and put it to the back. So I did. If you double-click the stack an animation move the image to the back.

image

Live-Demo here

XAML-Code:

<UserControl x:Class="ImageStack.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="321" d:DesignWidth="416" xmlns:my="clr-namespace:TheOliver.Controls">

    <Grid x:Name="LayoutRoot" Background="White">
        <my:ImageStack Margin="12" x:Name="imageStack1" Background="Gray" >
            <Image Source="/ImageStack;Component/Assets/1.jpg" />
            <Image Source="/ImageStack;Component/Assets/2.jpg" />
            <Image Source="/ImageStack;Component/Assets/3.jpg" />
            <Image Source="/ImageStack;Component/Assets/4.jpg" />
            <Image Source="/ImageStack;Component/Assets/5.jpg" />

        </my:ImageStack>
    </Grid>
</UserControl>

Source-Code:

// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Threading;

namespace TheOliver.Controls
{
    public class ImageStack : Panel
    {
        public ImageStack()
        {
            _doubleClickTimer = new DispatcherTimer();
            _doubleClickTimer.Interval = new TimeSpan(0, 0, 0, 0, DoubleClickSpeedInMS);
            _doubleClickTimer.Tick += (s, e) =>
                {
                    _clickCount = 0;
                    _doubleClickTimer.Stop();
                };

            this.MouseLeftButtonUp += (s, e) =>
                {
                    if (_clickCount == 1)
                    {
                        // Doubleclick detected
                        HideCurrentImage();
                    }
                    else
                    {
                        _clickCount++;
                        _doubleClickTimer.Start();
                    }
                };

            _hideStoryboard.Completed += (s, e) =>
                {
                    this.Children.Remove(_removedImage);
                    this.Children.Insert(0, _removedImage);
                    ShowNextImage();
                };

            _showStoryboard.Completed += (s, e) =>
                {
                    _storyboardIsActive = false;
                };
        }

        Random _random = new Random();
        int _clickCount;
        DispatcherTimer _doubleClickTimer;
        Storyboard _hideStoryboard = new Storyboard();
        Storyboard _showStoryboard = new Storyboard();
        Image _removedImage;
        bool _storyboardIsActive = false;
        double _newX;
        double _newY;
        Size _finalSize;

        private void ShowNextImage()
        {
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, AnimationInMS);

            // Part 2
            DoubleAnimation xa2 = new DoubleAnimation();
            xa2.Duration = duration;
            xa2.To = -_newX;

            DoubleAnimation ya2 = new DoubleAnimation();
            ya2.Duration = duration;
            ya2.To = -_newY;

            _showStoryboard.Stop();
            _showStoryboard.Children.Clear();
            _showStoryboard.Duration = duration;
            _showStoryboard.Children.Add(xa2);
            _showStoryboard.Children.Add(ya2);

            TransformGroup tg = _removedImage.RenderTransform as TransformGroup;
            TranslateTransform tt2 = new TranslateTransform();
            tg.Children.Add(tt2);
            _removedImage.RenderTransform = tg;

            Storyboard.SetTarget(xa2, tt2);   //set Animation Target
            Storyboard.SetTargetProperty(xa2, new PropertyPath("X"));   // set Animation TargetProperty
            Storyboard.SetTarget(ya2, tt2);
            Storyboard.SetTargetProperty(ya2, new PropertyPath("Y"));

            if (this.Resources.Contains("showme"))
            {
                this.Resources.Remove("showme");
            }
            this.Resources.Add("showme", _showStoryboard);

            _showStoryboard.Begin();
        }

        bool _layouted = false;

        protected override Size ArrangeOverride(Size finalSize)
        {
            _finalSize = finalSize;

            if (!_layouted)
            {
                LayoutImages(_finalSize);
                _layouted = true;
            }
            return base.ArrangeOverride(finalSize);
        }

        private void HideCurrentImage()
        {
            if (_storyboardIsActive)
            {
                return;
            }

            _storyboardIsActive = true;
            _removedImage = this.Children[this.Children.Count - 1] as Image;
            if (_removedImage != null)
            {
                TimeSpan duration = new TimeSpan(0, 0, 0, 0, AnimationInMS);

                double angle = _random.Next(360);
                _newX = Math.Sin(angle) * this.RenderSize.Width;
                _newY = Math.Cos(angle) * this.RenderSize.Height;

                _hideStoryboard.Stop();
                _hideStoryboard.Children.Clear();

                // Part 1
                DoubleAnimation xa1 = new DoubleAnimation();
                xa1.Duration = duration;
                xa1.To = _newX;      

                DoubleAnimation ya1 = new DoubleAnimation();
                ya1.Duration = duration;
                ya1.To = _newY;

                _hideStoryboard.Duration = duration;
                _hideStoryboard.Children.Add(xa1);
                _hideStoryboard.Children.Add(ya1);

                TransformGroup tg = _removedImage.RenderTransform as TransformGroup;

                TranslateTransform tt = new TranslateTransform();
                tg.Children.Add(tt);
                _removedImage.RenderTransform = tg;

                Storyboard.SetTarget(xa1, tt);
                Storyboard.SetTargetProperty(xa1, new PropertyPath("X"));
                Storyboard.SetTarget(ya1, tt);
                Storyboard.SetTargetProperty(ya1, new PropertyPath("Y"));

                if (this.Resources.Contains("hideme"))
                {
                    this.Resources.Remove("hideme");
                }
                this.Resources.Add("hideme", _hideStoryboard);

                _hideStoryboard.Begin();
            }
        }

        private Size LayoutImages(Size finalSize)
        {
            var images = this.Children.OfType<Image>();
            Random rnd = new Random();

            foreach (var image in images)
            {
                // Drop Shadow Effect
                if (ShowDropShadowEffect)
                {
                    DropShadowEffect dse = new DropShadowEffect();
                    dse.ShadowDepth = 0.3;
                    image.Effect = dse;
                }

                // Center image
                image.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                image.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;

                TransformGroup tg = new TransformGroup();

                // Scale to fit the finalsize * 90%
                image.Stretch = Stretch.Uniform;
                image.Width = finalSize.Width * ResizeFactor;
                image.Height = finalSize.Height * ResizeFactor;

                image.Margin = new Thickness(
                    (finalSize.Width - image.Width) / 2, (finalSize.Height - image.Height) / 2,
                    (finalSize.Width - image.Width) / 2, (finalSize.Height - image.Height) / 2);

                // Rotate image
                RotateTransform rt = new RotateTransform();
                rt.Angle = 90 - rnd.Next(180);
                rt.CenterX = image.Width / 2;
                rt.CenterY = image.Height / 2;
                tg.Children.Add(rt);

                image.RenderTransform = tg;
            }
            return finalSize;
        }

        #region Properties

        public double ResizeFactor
        {
            get { return (double)GetValue(ResizeFactorProperty); }
            set { SetValue(ResizeFactorProperty, value); }
        }

        public static readonly DependencyProperty ResizeFactorProperty =
            DependencyProperty.Register(
                "ResizeFactor",
                typeof(double),
                typeof(ImageStack),
                new PropertyMetadata(0.5, OnValueChanged));

        private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ImageStack stack = sender as ImageStack;
            stack.InvalidateArrange();
        }

        public bool ShowDropShadowEffect
        {
            get { return (bool)GetValue(ShowDropShadowEffectProperty); }
            set { SetValue(ShowDropShadowEffectProperty, value); }
        }

        public static readonly DependencyProperty ShowDropShadowEffectProperty =
            DependencyProperty.Register(
                "ShowDropShadowEffect",
                typeof(bool),
                typeof(ImageStack),
                new PropertyMetadata(true, OnValueChanged));

        public int DoubleClickSpeedInMS
        {
            get { return (int)GetValue(DoubleClickSpeedInMSProperty); }
            set { SetValue(DoubleClickSpeedInMSProperty, value); }
        }

        public static readonly DependencyProperty DoubleClickSpeedInMSProperty =
            DependencyProperty.Register(
                "DoubleClickSpeedInMS",
                typeof(int),
                typeof(ImageStack),
                new PropertyMetadata(500, OnDoubleClickSpeedChanged));

        private static void OnDoubleClickSpeedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ImageStack stack = sender as ImageStack;
            stack._doubleClickTimer.Stop();
            stack._doubleClickTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)e.NewValue);
        }

        public bool EnableDragging
        {
            get { return (bool)GetValue(EnableDraggingProperty); }
            set { SetValue(EnableDraggingProperty, value); }
        }

        public static readonly DependencyProperty EnableDraggingProperty =
            DependencyProperty.Register(
                "EnableDragging",
                typeof(bool),
                typeof(ImageStack),
                new PropertyMetadata(false));

        public int AnimationInMS
        {
            get { return (int)GetValue(AnimationInMSProperty); }
            set { SetValue(AnimationInMSProperty, value); }
        }

        public static readonly DependencyProperty AnimationInMSProperty =
            DependencyProperty.Register(
                "AnimationInMS",
                typeof(int),
                typeof(ImageStack),
                new PropertyMetadata(125));

        #endregion

    }
}

Download Sourcecode
Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, English, Expression, Silverlight, Visual Studio

Daily Demo: Image Spindle

March 16th, 2010

There are a lot of carousel controls out there, but I didn’t find any control which can be customized easy without re-coding or “hacking” hard-coded links to images. What I want is a control that can be customized from the design-interface or in XAML, but not in code.

So I created based on a sample on the web a really reusable carousel with mouse control to move it to the left or right.

And … very important you can insert as much pictures as you want, and change different other parameters like radius

image

 

A spindle with five images ….

image

A spindle with ten images … and no code change.

Live-Preview here

Xaml-Code:

<UserControl x:Class="ImageSpindle.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:my="clr-namespace:TheOliver.Controls">

    <Grid x:Name="LayoutRoot" Background="White">
        <my:ImageSpindle Margin="12" x:Name="imageSpindle1">
            <Image Source="Assets/1.jpg" />
            <Image Source="Assets/2.jpg" />
            <Image Source="Assets/3.jpg" />
            <Image Source="Assets/4.jpg" />
            <Image Source="Assets/5.jpg" />
        </my:ImageSpindle>
    </Grid>
</UserControl>

 

Control-Sourcecode:

using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace TheOliver.Controls
{
    public class ImageSpindle : Panel
    {
        Point _mousePoint;
        double _height;
        double _width;
        bool _isMouseOver;

        public ImageSpindle()
        {
            this.Loaded += (s, e) =>
                {
                    if (DesignerProperties.GetIsInDesignMode(this))
                    {
                        return;
                    }

                    this.MouseMove += (s1, e1) =>
                        {
                            _mousePoint = e1.GetPosition(this);
                        }; 

                    CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
                };

            this.MouseEnter += (s, e) =>
                {
                    _isMouseOver = true;
                };

            this.MouseLeave += (s, e) =>
                {
                    _isMouseOver = false;
                };
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            _height = availableSize.Height;
            _width = availableSize.Width;

            var images = this.Children.OfType<Image>();
            int imageCount = images.Count();
            if (imageCount > 0)
            {
                double step = 360.0 / imageCount;
                double currentStep = 0;
                foreach (var image in images)
                {
                    UpdateImage(image, currentStep);
                    currentStep += step;
                }
            }
            return base.MeasureOverride(availableSize);
        }

        private Image UpdateImage(Image image, double step)
        {
            image.Height = ImageHeight;
            image.Width = ImageWidth;
            image.Margin = new Thickness(
                (_width - ImageWidth) / 2, (_height - ImageHeight) / 2,
                (_width - ImageWidth) / 2, (_height - ImageHeight) / 2);
            image.RenderTransformOrigin = new Point(0.5, 0.5);
            image.Stretch = ImageStretch;

            PlaneProjection pp = new PlaneProjection();
            pp.CenterOfRotationZ = SpindleCenterOfRotation;
            pp.RotationY = step;
            image.Projection = pp;

            return image;
        }

        void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            if (StopWhenMouseLeft)
            {
                if (!_isMouseOver)
                {
                    return;
                }
            }

            if (double.IsNaN(_width) || _width == 0)
            {
                return;
            }

            foreach (var image in this.Children.OfType<Image>())
            {
                PlaneProjection pp = image.Projection as PlaneProjection;
                if (pp != null)
                {
                    pp.RotationY += ((_mousePoint.X - (_width / 2)) / _width) * 10;
                }
                image.Opacity = (_mousePoint.Y / _height) * 0.5 + 0.5;
            }
        }

        #region Properties

        public Stretch ImageStretch
        {
            get { return (Stretch)GetValue(ImageStretchProperty); }
            set { SetValue(ImageStretchProperty, value); }
        }

        public static readonly DependencyProperty ImageStretchProperty =
            DependencyProperty.Register(
                "ImageStretch",
                typeof(Stretch),
                typeof(ImageSpindle),
                new PropertyMetadata(Stretch.Uniform, OnValueChanged));

        public double ImageWidth
        {
            get { return (double)GetValue(ImageWidthProperty); }
            set { SetValue(ImageWidthProperty, value); }
        }

        public static readonly DependencyProperty ImageWidthProperty =
            DependencyProperty.Register(
                "ImageWidth",
                typeof(double),
                typeof(ImageSpindle),
                new PropertyMetadata(160.0, OnValueChanged));

        public double ImageHeight
        {
            get { return (double)GetValue(ImageHeightProperty); }
            set { SetValue(ImageHeightProperty, value); }
        }

        public static readonly DependencyProperty ImageHeightProperty =
            DependencyProperty.Register(
                "ImageHeight",
                typeof(double),
                typeof(ImageSpindle),
                new PropertyMetadata(120.0, OnValueChanged));

        public double SpindleCenterOfRotation
        {
            get { return (double)GetValue(SpindleCenterOfRotationProperty); }
            set { SetValue(SpindleCenterOfRotationProperty, value); }
        }

        public static readonly DependencyProperty SpindleCenterOfRotationProperty =
            DependencyProperty.Register(
                "SpindleCenterOfRotation",
                typeof(double),
                typeof(ImageSpindle),
                new PropertyMetadata(-160.0, OnValueChanged));

        private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            ImageSpindle spindle = sender as ImageSpindle;
            spindle.InvalidateMeasure();
        }

        public bool StopWhenMouseLeft
        {
            get { return (bool)GetValue(StopWhenMouseLeftProperty); }
            set { SetValue(StopWhenMouseLeftProperty, value); }
        }

        public static readonly DependencyProperty StopWhenMouseLeftProperty =
            DependencyProperty.Register(
                "StopWhenMouseLeft",
                typeof(bool),
                typeof(ImageSpindle),
                new PropertyMetadata(true));

        #endregion

    }
}

 

Download-Source

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, English, Silverlight, Visual Studio

Daily Demo: Tipping Text

March 15th, 2010

Based on a true story, I built a small control for Silverlight to tip text, like an old fashioned typewriter.

image

Liveversion: here.

Code for the Control:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace TheOliver.Controls
{
    public class TippingText : UserControl
    {
        TextBox _textblock;
        DispatcherTimer _timer;

        public TippingText()
        {
            _textblock = new TextBox();

            this.Content = _textblock;

            _timer = new DispatcherTimer();

            _timer.Interval = new TimeSpan(0, 0, 0, 0, TippingSpeedInMilliseconds);
            _timer.Tick += (s, e) =>
                {
                    ShowNextCharacter();
                    _currentCharacter++;
                    if (_currentCharacter >= Text.Length)
                    {
                        _timer.Stop();
                        if (Repeat)
                        {
                            _currentCharacter = 0;
                            _timer.Start();
                        }
                    }
                };

            this.Loaded += (s, e) =>
                {
                    if (Text.Length > 0)
                    {
                        _timer.Start();
                    }
                };
        }

        private void ShowNextCharacter()
        {
            if (Text.Length > _currentCharacter + 1)
            {
                _textblock.Text = Text.Substring(0, _currentCharacter + 1);
            }
        }

        private int _currentCharacter;

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register(
                "Text",
                typeof(string),
                typeof(TippingText),
                new PropertyMetadata("No Text", OnValueChanged));

        private static void OnValueChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            TippingText tt = sender as TippingText;
            tt._timer.Stop();
            tt._timer.Interval = new TimeSpan(0, 0, 0, 0, tt.TippingSpeedInMilliseconds);
            tt._currentCharacter = 0;
            tt._textblock.TextWrapping = tt.TextWrapping;
            tt._textblock.TextAlignment = tt.TextAlignment;
            tt._textblock.Text = tt.Text;
            if (tt.Text.Length > 0)
            {
                tt._timer.Start();
            }
        }

        public int TippingSpeedInMilliseconds
        {
            get { return (int)GetValue(TippingSpeedInMillisecondsProperty); }
            set { SetValue(TippingSpeedInMillisecondsProperty, value); }
        }

        public static readonly DependencyProperty TippingSpeedInMillisecondsProperty =
            DependencyProperty.Register(
                "TippingSpeedInMilliseconds",
                typeof(int),
                typeof(TippingText),
                new PropertyMetadata(200, OnValueChanged));

        public bool Repeat
        {
            get { return (bool)GetValue(RepeatProperty); }
            set { SetValue(RepeatProperty, value); }
        }

        public static readonly DependencyProperty RepeatProperty =
            DependencyProperty.Register(
                "Repeat",
                typeof(bool),
                typeof(TippingText),
                new PropertyMetadata(true, OnValueChanged));

        public TextWrapping TextWrapping
        {
            get { return (TextWrapping)GetValue(TextWrappingProperty); }
            set { SetValue(TextWrappingProperty, value); }
        }

        public static readonly DependencyProperty TextWrappingProperty =
            DependencyProperty.Register(
                "TextWrapping",
                typeof(TextWrapping),
                typeof(TippingText),
                new PropertyMetadata(TextWrapping.Wrap, OnValueChanged));

        public TextAlignment TextAlignment
        {
            get { return (TextAlignment)GetValue(TextAlignmentProperty); }
            set { SetValue(TextAlignmentProperty, value); }
        }

        public static readonly DependencyProperty TextAlignmentProperty =
            DependencyProperty.Register(
                "TextAlignment",
                typeof(TextAlignment),
                typeof(TippingText),
                new PropertyMetadata(TextAlignment.Center, OnValueChanged));

    }
}

Download Sourcecode

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, English, Silverlight

Wechseln in Vollbild-Modus und wieder zurück mit Trigger

October 14th, 2009

Oft fragt man sich, wie man in Expression Blend einfach mal eine Funktion in seine Anwendung integrieren kann, ohne dafür extra Code schreiben zu müssen.

Ein solcher Fall ist z.B. der Wechsel in den Vollbildmodus und wieder zurück. Mit dem folgenden Trigger “FullScreenAction” kann man so etwas ohne Code in Blend durchführen.

Vorrausgesetzt, man hat die Klasse unten in seinem Projekt integriert oder referenziert.

image

using System.Windows;
using System.Windows.Interactivity;

namespace Oliver.Controls.Behaviors
{
    public class FullScreenAction
        : TargetedTriggerAction<FrameworkElement>
    {
        protected override void Invoke(object o)
        {
            Application.Current.Host.Content.IsFullScreen =
                !Application.Current.Host.Content.IsFullScreen;

        }
    }
}

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Silverlight , ,

Objekte mit dem Mausrad vergrößern und verkleiner

October 14th, 2009

Eines der neuen Features von Silverlight 3 und Expression Blend 3 sind die Behaviors. Mit diesen Behaviors lassen sich sehr einfach “generische” Funktionalität erstellen, die man dann auf andere Objekte übertragen kann.

Das folgende Beispiel, soll mit Hilfe des Mausrades, Objekte vergrößern und verkleinern. Geht man mit der Maus auf ein bestimmtes Objekt und dreht dann am Mausrad, dann wird dieses Objekt größer oder kleiner. Verläßt die Maus den Fokus, dann wird das Objekt wieder auf Normalgröße gesetzt.

Vorher:

image

Nachher:

image

Damit man das ganze in Blend einfach verwenden kann, muss die unten beschriebene Klasse im aktuellen Projekt integriert oder referenziert sein.

image

Code für die Behavior-Klasse:

using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;

namespace Oliver.Behaviors
{
    public class MouseMagnifier : Behavior<FrameworkElement>
    {
        FrameworkElement _target;
        ScaleTransform _scale;

        private double _scaleFactor = 0.2;
        public double ScaleFactor
        {
            get { return _scaleFactor; }
            set { _scaleFactor = value; }
        }

        protected override void OnAttached()
        {
            _target = this.AssociatedObject;
            _target.MouseWheel += new MouseWheelEventHandler(_target_MouseWheel);
            _target.MouseLeave += new MouseEventHandler(_target_MouseLeave);

            _scale = new ScaleTransform();
            _target.RenderTransform = _scale;
            base.OnAttached();
        }

        void _target_MouseLeave(object sender, MouseEventArgs e)
        {
            _scale.ScaleX = 1;
            _scale.ScaleY = 1;
        }

        void  _target_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (e.Delta > 0)
            {
                _scale.ScaleX += _scaleFactor;
                _scale.ScaleY += _scaleFactor;
            }
            else
            {
                _scale.ScaleX -= _scaleFactor;
                _scale.ScaleY -= _scaleFactor;
            }   
        }

    }
}

XAML-Code für die UI:

<UserControl
    xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:Oliver_Behaviors="clr-namespace:Oliver.Behaviors;assembly=Oliver.Controls.Silverlight.Behaviors" x:Class="Oliver.Apps.ControlTester.Samples.MouseMagnifierBehaviorSample"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">

        <Rectangle Stroke="Black" Height="66" HorizontalAlignment="Left" Margin="29,56,0,0" VerticalAlignment="Top" Width="126">
            <i:Interaction.Behaviors>
                <Oliver_Behaviors:MouseMagnifier/>
            </i:Interaction.Behaviors>
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="White" Offset="1"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Button Height="54" HorizontalAlignment="Right" Margin="0,56,69,0" VerticalAlignment="Top" Width="99" Content="Button">
            <i:Interaction.Behaviors>
                <Oliver_Behaviors:MouseMagnifier/>
            </i:Interaction.Behaviors>
        </Button>
        <TextBox Height="29" Margin="179,0,95,106" VerticalAlignment="Bottom" Text="TextBox" TextWrapping="Wrap">
            <i:Interaction.Behaviors>
                <Oliver_Behaviors:MouseMagnifier/>
            </i:Interaction.Behaviors>
        </TextBox>
        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top" Text="Use Mousewheel over Controls to resize them. " TextWrapping="Wrap"/>

    </Grid>
</UserControl>

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Silverlight , ,

Silverlight 3 Karussel veröffentlicht

August 24th, 2009

Ich hab mal wieder ein neues Steuerelement (inkl. Design-Time-Experience) erstellt.

image_thumb[1]

Mehr Infos und den Download dazu gibt es hier.

http://the-oliver.com/projects/apps/sl3linkcarousel

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Silverlight

Erstellen eines Hintergrund-Steuerelements

August 18th, 2009

In Expression Blend und diversen anderen Anwendungen, findet man immer wieder Hintergründe die nach einer Art Schachmuster aufgebaut sind.

image

Ich persönlich finde, das dies sehr nett anzusehen ist. Allerdings frag ich ich dann auch immer, wie haben die das gemacht, und vor allem wie kann ich das in meiner eigenen Anwendung übernehmen.

Dazu habe ich dann mal ein eigenes Steuerelement entwickelt, das bereits in der Entwicklungsumgebung zeigt, wie es später aussehen wird. Man kann dieses über typische Eigenschaften, wie Foreground, Background, Gap (Zwischenraum zwischen Rechtecken), RectWidth (Breite eines Vierecks) und RectHeight (Höhe eines Vierecks) anzeigen.

Anbei einige Ausprägungen des fertigen Steuerelementes (RectangleArea).

image

Der Code für dieses Steuerelement ist recht einfach:

using System.Windows;

using System.Windows.Controls;

using System.Windows.Shapes;

 

namespace Oliver.Controls

{

    public class RectangleArea : UserControl

    {

        #region Dependency properties

        

        public static readonly DependencyProperty GapProperty =

            DependencyProperty.Register(

                "Gap",

                typeof(double),

                typeof(RectangleArea),

                new PropertyMetadata(5d, OnValueChanged));

 

        public double Gap

        {

            get { return (double)GetValue(GapProperty); }

            set { SetValue(GapProperty, value); }

        }

 

        public static readonly DependencyProperty RectWidthProperty =

            DependencyProperty.Register(

                "RectWidth",

                typeof(double),

                typeof(RectangleArea),

                new PropertyMetadata(5d, OnValueChanged));

 

        public double RectWidth

        {

            get { return (double)GetValue(RectWidthProperty); }

            set { SetValue(RectWidthProperty, value); }

        }

 

        public static readonly DependencyProperty RectHeightProperty =

            DependencyProperty.Register(

                "RectHeight",

                typeof(double),

                typeof(RectangleArea),

                new PropertyMetadata(5d, OnValueChanged));

 

        public double RectHeight

        {

            get { return (double)GetValue(RectHeightProperty); }

            set { SetValue(RectHeightProperty, value); }

        }

 

        #endregion

 

        #region Internal

 

        private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)

        {

            RectangleArea panel = (RectangleArea)sender;

            panel.UpdateLayout();

        }

 

        protected override Size MeasureOverride(Size availableSize)

        {

            DrawContent(availableSize.Width, availableSize.Height);

            return base.MeasureOverride(availableSize);

        }

 

        private void DrawContent(double width, double height)

        {

            Canvas canvas = new Canvas();

            canvas.Background = this.Background;

            

            RectWidth = RectWidth == 0 ? 1 : RectWidth;

            RectHeight = RectHeight == 0 ? 1 : RectHeight;

            

            double xd = width / (RectWidth + Gap);

            double yd = height / (RectHeight + Gap);

            

            for (int x = 0; x < xd; x++)

            {

                bool alternatingX = x % 2 == 0;

                for (int y = 0; y < yd; y++)

                {

                    bool alternatingY = y % 2 == 0;

 

                    Rectangle r = new Rectangle();

 

                    if ((alternatingX & !alternatingY) ||

                        (!alternatingX & alternatingY))

                    {

                        continue;

                    }

                    double left = x * (RectWidth + Gap);

                    double top = y * (RectHeight + Gap);

                    r.SetValue(Canvas.LeftProperty, left);

                    r.SetValue(Canvas.TopProperty, top);

                    r.Width = RectWidth;

                    r.Height = RectHeight;

                    r.Fill = this.Foreground;

 

                    canvas.Children.Add(r);

                }

            }

 

            this.Content = canvas;

        }

 

        #endregion

    }

}

Das Anordnen der Elemente geschieht in der Methode DrawContent. Diese wird jedesmal aufgerufen, wenn sich ein Wert ändert.

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, Silverlight

Windows 7 Code Contest und 17.777 $ gewinnen

July 17th, 2009

Windows 7 wird richtig, richtig, richtig gut. Zeigt wie gut ihr Anwendungen entwickeln könnt und gewinnt Schotter, Kies, Cash, Money, Piepen, Moneten, Kohle, Asche, Moss und Zaster.

Link: https://www.code7contest.com/ 

image

Ich darf leider nicht teilnehmen.

Social:
  • Print this article!
  • del.icio.us
  • Facebook
  • Twitter

Developer, Windows ,