Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

Header Checkbox event to check all other chechboxes inside columns of a listview

$
0
0

when i click in a chechbox inside a column's header it turns all other checkboxes inside columns to true which they are bound to a bool property "IsChecked" and when i uncheck the other checkboxes value took false. but i have a display problem that my checkboxes doesn't check the case are still empty when i check all. here is my code 

<GridViewColumn.Header><CheckBox Checked="HeaderChk_Checked" Unchecked="HeaderChk_Checked"/></GridViewColumn.Header><GridViewColumn.CellTemplate><DataTemplate><CheckBox IsChecked="{Binding IsChecked, Mode = TwoWay}"></CheckBox></DataTemplate></GridViewColumn.CellTemplate>
private void HeaderChk_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            if (chk.IsChecked == true)
            {
                for (int i = 0; i < listView.Items.Count; i++)
                {
                    dynamic currentItemLoop = listView.Items[i];
                    currentItemLoop.IsChecked = true;
                }
            }
            else
            {
                {
                    for (int i = 0; i < listView.Items.Count; i++)
                    {
                        dynamic currentItemLoop = listView.Items[i];
                        currentItemLoop.IsChecked = false;
                    }
                }
            }
        }
when i tried t ogive to my checkbox a name and access it in my c# code it doesnt work. any help to turn all checkboxes to isChecked ? 

 

How to SelectAll in TextBox when TextBox gets focus by mouse click?

$
0
0

If you click into the adress bar of the internet explorer, the adress will get selected. Only the second click sets the caret into the mouse position.

 

I'd like to have this in my TextBox. I tried to override OnGotFocus and call SelectAll(), but this only works if the TextBox gets it focus by keyboard. If the TextBox is clicked by mouse, the text is selected for a split second, then it is deselected again and the caret is set.

 

Thanks,
Sam

wpf loading bar loaded opening new window

$
0
0

hi! so, my plan is to have a "loadingscreen" with a loadingbar. i have all that, i even have the code for the animation to let it seem like it's loading. the problem is, that it doesn't open a new window after the "loading" is completed. and i've been stuck on this for a while now.

this is the code i have for the animation and the not working code to show a new window:

 public loadingscreen()
        {
            InitializeComponent();
            Loadprogressbar();
        }

        private void Loadprogressbar()
        {
            pbLoading.Value = 0;
            pbLoading.Maximum = 100;

            Duration duration = new Duration(TimeSpan.FromSeconds(30));
            DoubleAnimation dblanim = new DoubleAnimation(200.0, duration);
            pbLoading.BeginAnimation(ProgressBar.ValueProperty, dblanim);

            if (pbLoading.Value == pbLoading.Maximum)
            {
                MasterMind MasterMind = new MasterMind();
                MasterMind.Show();
                this.Close();
            }
what it does now if i start up the program, is that, it "loads", but it doesn't open any new windows. it just, stays "fully loaded"

do i maybe have to say something like "if the animation is done, after the 30 seconds, do this"?

Powershell WPF window sizes Different when run outside of PS ISE.

$
0
0

Hey there,

I am currently working on a Powershell GUI Script utilising WPF. The problem Im having is that within the ISE when I run the script it all looks great. When I right click on the script from within the desktop environment and select "Run with Powershell", the windows are cropped. This occurs on all windows (Almost 20 windows in all).

I Would Ideally like to have the windows look exactly the same from whichever environment it is launched from. 

I have tried modifying the "MinHeight" and "MinWidth" properties within the XAML, but that pushes out the borders from within ISE.

The Resize option is set to "No Resize".

Any Help Would be Great.

Thanks.

J.

 

ScrollBar Thumb not working (after applying template)- WPF

$
0
0

Hi,

   I have a scrollbar for whichi I  am applying template and the XAML is given below. I have two questions from the below XAML. 

  •     When I drag the thumb, its not moving.
  •     How to increase the size of Thumb>
<ScrollBar Minimum="0" Maximum="100" Orientation="Vertical" Grid.Column="4"><ScrollBar.Style><Style TargetType="ScrollBar"><Setter Property="Template"><Setter.Value ><ControlTemplate TargetType="ScrollBar"><Grid ><Grid.RowDefinitions><RowDefinition Height="20"/><RowDefinition Height="*"/><RowDefinition Height="20"/></Grid.RowDefinitions><RepeatButton Command="ScrollBar.PageUpCommand" Content="up"/><Track Name="trck" IsDirectionReversed="true" Grid.Row="1"><Track.IncreaseRepeatButton ><RepeatButton Command="ScrollBar.PageDownCommand" Opacity="0" Background="Transparent"  /></Track.IncreaseRepeatButton><Track.Thumb ><Thumb   Foreground="Red"><Thumb.Style><Style  TargetType="Thumb"><Setter Property="Height" Value="30"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Thumb"><Ellipse Fill="Orange" Width="20" Height="30"/></ControlTemplate></Setter.Value></Setter></Style></Thumb.Style></Thumb></Track.Thumb><Track.DecreaseRepeatButton ><RepeatButton Command="ScrollBar.PageUpCommand" Opacity="0" Background="Transparent"  /></Track.DecreaseRepeatButton></Track><RepeatButton Content="Dn" Command="ScrollBar.PageDownCommand" Grid.Row="2"/></Grid></ControlTemplate></Setter.Value></Setter></Style></ScrollBar.Style></ScrollBar>

I couldnt see my orange color Ellipse (inside the Thumb) even after increasing hte size.

Kindly help me in above two questions.

Sanjay.

wpf c# word processor with richtextbox, does word have individual richtextboxes for each page and place several richtextboxes in a gui with a scroll bar

$
0
0

word processor with richtextbox, does word software have individual richtextboxes for each page and place several richtextboxes in a gui with a scroll bar. what type of gui contains all the richtextboxes?

Mike

ListBox KeyDown Event does not raise for Key.Down or Key.Up

$
0
0

I have a list box with two items in it. Only one item is ever in view. the up and down arrow keys will cycle through the two items but stop when they reach the top and bottom of the list box. i wanted to extend this funtionality to start over when the list box is at the top or bottom. My list box has AM and PM in it. This list box is part of a custom TimeUpDown control i am making. I added a KeyDown and KeyUp event to my ListBox control. when i press the Up arrow key e.g. (Key.Up) the KeyDown event is not Raised, but the KeyUp event is raised. if i press the "D" key e.g. (Key.D) both the KeyDown and KeyUp events get raised. Why is the Key.Down and Key.Up being blocked from raising the KeyDown event of the ListBox control.


.Chris

Throttle in TextBox TextChange event

$
0
0

On codebehind of textbox we have some logic running. every time a next text is added in textbox corresponding Textchange event is fired and logic runs.

I am willing to have some Throttle introduced if 2 characters are typed very fast ( within 10 ms) than Textchange event should fire only once.  How do I start achieving this.


EF6 and partial classes

$
0
0

Hi all,
I created a WPF solution.
I then created a folder (named Logic) to insert a edmx file mapped to a sqlserver 2014 database.
Now, I would like to add my partial class (named Customer) in the Logic folder to extend my business logic.
In this way EF classes and my will join together.

But when I add my class Customer, VS said that within the Logic folder already exists a class called Customer (in fact there is one that creates EF in defalut).

What should I do now?
In VS 2010  was not this problem

thank you so much

d.

How can I get System.Speech SpeakProgress to highlight spoken words in WPF RichTextbox

$
0
0

Hi, I have tried everything to get System.Soeech to highlight the spoken words in a WPF RichTextBox and have failed . . .

I am using a TextRange to Speak the text of the WPF RichTextBox - no problem there!

But SpeakProgress - e.CharacterPosition does not correspond to the character position in the WPF RichTextBox

I got this far in the SpeakProgress() method, but it keeps highlighting the wrong words

TextRange text = new TextRange(start, this.CurrentlySpeakingRichTextBox.Document.ContentEnd);
                        TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);

                        while (current != null)
                        {
                            string textInRun = current.GetTextInRun(LogicalDirection.Forward);

                            if (!string.IsNullOrWhiteSpace(textInRun))
                            {
                                int index = textInRun.IndexOf(aWord);
                                if (index != -1)
                                {
                                    TextPointer selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward);
                                    TextPointer selectionEnd = selectionStart.GetPositionAtOffset(aWord.Length, LogicalDirection.Forward);
                                    TextRange selection = new TextRange(selectionStart, selectionEnd);
                                    this.RichTextBoxPointer = selectionStart;
                                    this.CurrentlySpeakingRichTextBox.Selection.Select(selection.Start, selection.End);
                                   // rtb.Focus();
                                }
                            }
                            current = current.GetNextContextPosition(LogicalDirection.Forward);
                        }

Please, anyone  . . . Help!


WPF InkCanvas

$
0
0
I want to use InkCanvas kind of functionality in WPF canvas, means I want to draw a free hand line or text on Canvas. Ultimately I want to draw text with the pencil and an algorithm of style 'InkRecognition' will convert freehand text in printed text directly in the canvas. Using the eraser I can be able to erase some characters and possibly replace with preprint text or freehand characters.
If I am using textblock for the printed text I won't be able to write over the text or erase characters using the eraser.

wpf datavisualization chart

$
0
0

Hi ,

Kindly let me know how to bind time scale value (12 am to 12 am) in Char Line series x Axis.How to set here Min,Max value and Intervals

Following is my code

 <my:Chart.Axes>
<my:LinearAxis x:Name="ChartLineSeries" Background="Azure" Foreground="Blue" FontWeight="DemiBold" Orientation="X"  Title="Time" ShowGridLines="False" Margin="0,0,0,-8"/>
</my:Chart.Axes>

Thanks in Advance


Efforts may fail but don't fail to take effort -------------- sidd

XAML designer in new WPF project throws System.Argument.Exception upfront in new solution

$
0
0

Hi,

I am using Visual Studio 2015 Community Edition. I worked with a few WPF projects. The projects themselves still compile and run in VS, it is just the XAML Designer that suddenly does not work any longer.

This does not seem to be related to the projects, as I first thought.

When I create a NEW WPF project in the "New Project" C# dialog window, the XAML Designer brings an exception upfront, as shown below.

A "repair" for VS 2015 from control panel, programs and features, which took at least 90 minutes, did not help.

After googling the exception I realized this occurs often. Yet nowhere did I find a solution. It goes like this:

An Unhandled Exception has occurred.                                             

Click here to reload the designer (which does not remedy anything).

Details

System.ArgumentException

An item with the same key has already been added.

   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)   at Microsoft.VisualStudio.DesignTools.Utility.Telemetry.VsTelemetryService.RegisterDesignerProcessSession(Int32 pid)   at Microsoft.VisualStudio.DesignTools.Utility.Feedback.WatsonTracker.RegisterSession(Int32 processID)   at Microsoft.VisualStudio.DesignTools.Utility.DesignerSessionTracker.RecordDesignerStart(Int32 processID, String isolationTargetIdentifier, Boolean mockCustomTypes, String buildConfiguration)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, IIsolationTarget isolationTarget, String baseDirectory)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()   at Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func`2 func, CancellationToken cancelToken)   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0`1.<StartTask>b__0()   at System.Threading.Tasks.Task`1.InnerInvoke()   at System.Threading.Tasks.Task.Execute()


How can this be in a newly created WPF project within a virgin solution?

As this is a specialized forum on Windows Presentation Foundation, perhaps s.b. here knows?

Actually, Microsoft should be interested in a solution themselves, as this should not occur after starting a new WPF project in a new solution.

Thx for any hints.



Andreas





Multi Level Virtualisation

$
0
0

Hello everyone,

I'm wondering if there is a concept about virtualisation in multi level structures.

I have a ListView that contains elements that CAN contain another ListView. Out of the box only the toplevel Listview supports virtualisation.

Are there any solutions to get the sublists to virtualize too?

<ListView ItemsSource="{Binding Items}" VirtualizingStackPanel.IsVirtualizing="True"
                      VirtualizingStackPanel.VirtualizationMode="Standard"><ListView.ItemTemplate><DataTemplate><StackPanel><TextBox Text="{Binding Name}" /><!-- SubList--><ListView ItemsSource="{Binding Items}" VirtualizingStackPanel.IsVirtualizing="True"
                                      VirtualizingStackPanel.VirtualizationMode="Standard"><ListView.ItemTemplate><DataTemplate><TextBox Text="{Binding Name}" /></DataTemplate></ListView.ItemTemplate></ListView></StackPanel></DataTemplate></ListView.ItemTemplate></ListView>


ArgumentOutOfRangeException during drag and drop using toucn event in Tablet

$
0
0

Hi all, I run the application in tablet device and it works well for mouse event (using pen also) but get exception when using touch.

The exception happened when swapping the data. Maybe I need to add some validation to handle this exception for touch event?

I have added log and generate into C drive, when u copy the exe to tablet, make sure you are running as administrator.

Download Project

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at System.Collections.ObjectModel.Collection`1.get_Item(Int32 index)
   at FM.UI.View.PanelTypicalParameterCustomization_View.DragDropHelper_ItemDropped(Object sender, DragDropEventArgs e)
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index.


Window1.xaml.cs

using System;
using System.IO;
using System.Windows;

namespace Clarity.Demo.GenericDragDrop
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new Window1ViewModel();
            DragDropHelper.ItemDropped += DragDropHelper_ItemDropped;
            Unloaded += Window1_Unloaded; ;
        }

        private void Window1_Unloaded(object sender, RoutedEventArgs e)
        {
            DragDropHelper.ItemDropped -= DragDropHelper_ItemDropped;
        }

        private void DragDropHelper_ItemDropped(object sender, DragDropEventArgs e)
        {
            try
            {
                Window1ViewModel viewModel = DataContext as Window1ViewModel;

                //causing exception An ItemsControl is inconsistent with its items source
                //viewModel.Persons.RemoveAt(e.DragDataIndex);
                //viewModel.Persons.Insert(e.DragDataIndex, e.TargetData as Person);

                //viewModel.Persons.RemoveAt(e.TargetDataIndex);
                //viewModel.Persons.Insert(e.TargetDataIndex, e.DragData as Person);

                Person temp = e.TargetData as Person;
                int a = viewModel.Persons.IndexOf(temp);
                int b = viewModel.Persons.IndexOf(e.DragData as Person);
                viewModel.Persons[a] = viewModel.Persons[b];
                viewModel.Persons[b] = temp;
            }
            catch (Exception exception)
            {
                File.AppendAllText(@"C:\log.txt", string.Format("DragDropHelper_ItemDropped, exeception message: {0}\n", exception));
            }
        }
    }
}

Window1ViewModel.cs

using System.Collections.ObjectModel;

namespace Clarity.Demo.GenericDragDrop
{
    public class Window1ViewModel
    {
        private ObservableCollection<Person> persons;
        public ObservableCollection<Person> Persons
        {
            get
            {
                if (persons == null)
                {
                    persons = new ObservableCollection<Person>();
                    persons.Add(new Person("Mr A"));
                    persons.Add(new Person("Mr B"));
                    persons.Add(new Person("Mr C"));
                    persons.Add(new Person(string.Empty));
                    persons.Add(new Person(string.Empty));
                    persons.Add(new Person(string.Empty));
                    persons.Add(new Person(string.Empty));
                }
                return persons;
            }
        }

        public Window1ViewModel()
        {
            Persons.CollectionChanged += Persons_CollectionChanged;
        }

        private void Persons_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {

        }
    }
}

DragDropHelper.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace Clarity.Demo.GenericDragDrop
{
    public class DragDropHelper
    {
        private Point initialPoint;
        private Point delta;
        private Point scrollTarget;
        private object dropTarget;
        private object dragData;
        private int dropTargetIndex = -1;
        private int dragDataIndex = -1;
        private DataGrid selectedTarget;
        private DataGridRow selectedRow;
        private bool adornerCaptured;
        private UserControl topWindow;
        private Canvas dragDropAdornerLayer;
        private DragDropAdornerBase dragDropAdorner;
        private static DragDropHelper instance;
        private static DragDropHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new DragDropHelper();
                }
                return instance;
            }
        }

        public static bool GetIsDragSource(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsDragSourceProperty);
        }

        public static void SetIsDragSource(DependencyObject obj, bool value)
        {
            obj.SetValue(IsDragSourceProperty, value);
        }

        public static UIElement GetDragDropControl(DependencyObject obj)
        {
            return (UIElement)obj.GetValue(DragDropControlProperty);
        }

        public static void SetDragDropControl(DependencyObject obj, UIElement value)
        {
            obj.SetValue(DragDropControlProperty, value);
        }

        public static string GetAdornerLayer(DependencyObject obj)
        {
            return (string)obj.GetValue(AdornerLayerProperty);
        }

        public static void SetAdornerLayer(DependencyObject obj, string value)
        {
            obj.SetValue(AdornerLayerProperty, value);
        }

        public static string GetDropTarget(DependencyObject obj)
        {
            return (string)obj.GetValue(DropTargetProperty);
        }

        public static void SetDropTarget(DependencyObject obj, string value)
        {
            obj.SetValue(DropTargetProperty, value);
        }

        public static readonly DependencyProperty IsDragSourceProperty = DependencyProperty.RegisterAttached("IsDragSource", typeof(bool), typeof(DragDropHelper), new UIPropertyMetadata(false, IsDragSourceChanged));
        public static readonly DependencyProperty DragDropControlProperty = DependencyProperty.RegisterAttached("DragDropControl", typeof(UIElement), typeof(DragDropHelper), new UIPropertyMetadata(null));
        public static readonly DependencyProperty AdornerLayerProperty = DependencyProperty.RegisterAttached("AdornerLayer", typeof(string), typeof(DragDropHelper), new UIPropertyMetadata(null));
        public static readonly DependencyProperty DropTargetProperty = DependencyProperty.RegisterAttached("DropTarget", typeof(string), typeof(DragDropHelper), new UIPropertyMetadata(string.Empty));
        public static event EventHandler<DragDropEventArgs> ItemDropped;

        private static void IsDragSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var dragSource = d as UIElement;

            if (dragSource != null)
            {
                dragSource.PreviewMouseLeftButtonDown += Instance.DragSource_PreviewMouseLeftButtonDown;
                dragSource.PreviewMouseLeftButtonUp += Instance.DragSource_PreviewMouseLeftButtonUp;
                dragSource.PreviewMouseMove += Instance.DragSource_PreviewMouseMove;
                dragSource.PreviewTouchDown += Instance.DragSource_PreviewTouchDown;
                dragSource.PreviewTouchUp += Instance.DragSource_PreviewTouchUp;
                dragSource.PreviewTouchMove += Instance.DragSource_PreviewTouchMove;
            }
        }

        private void DragSource_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                DownSetup(sender, e.OriginalSource as Visual, e);
                Down(sender, e.GetPosition(selectedTarget));
            }
        }

        private void DragSource_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                if (!adornerCaptured && dragData != null)
                {
                    if (DragDropUIHelper.IsMovementBigEnough(initialPoint, e.GetPosition(topWindow)))
                    {
                        dragDropAdorner = (DragDropAdornerBase)GetDragDropControl(sender as DependencyObject);
                        dragDropAdorner.DataContext = dragData;
                        dragDropAdorner.Opacity = 0.8;

                        dragDropAdornerLayer.Visibility = Visibility.Visible;
                        dragDropAdornerLayer.Children.Clear();
                        dragDropAdornerLayer.Children.Add(dragDropAdorner);

                        adornerCaptured = Mouse.Capture(dragDropAdorner);

                        Canvas.SetLeft(dragDropAdorner, initialPoint.X - 20);
                        Canvas.SetTop(dragDropAdorner, initialPoint.Y - 15);

                        dragDropAdornerLayer.PreviewMouseMove += DragDropAdornerLayer_PreviewMouseMove;
                        dragDropAdornerLayer.PreviewMouseUp += DragDropAdornerLayer_PreviewMouseUp;
                    }
                }
            }
        }

        private void DragSource_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                Clear();
            }
        }

        private void DragSource_PreviewTouchDown(object sender, TouchEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                DownSetup(sender, e.OriginalSource as Visual, e);
                Down(sender, e.GetTouchPoint(selectedTarget).Position);
            }
        }

        private void DragSource_PreviewTouchMove(object sender, TouchEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                if (!adornerCaptured && dragData != null)
                {
                    if (DragDropUIHelper.IsMovementBigEnough(initialPoint, e.GetTouchPoint(topWindow).Position))
                    {
                        dragDropAdorner = (DragDropAdornerBase)GetDragDropControl(sender as DependencyObject);
                        dragDropAdorner.DataContext = dragData;
                        dragDropAdorner.Opacity = 0.7;

                        dragDropAdornerLayer.Visibility = Visibility.Visible;
                        dragDropAdornerLayer.Children.Clear();
                        dragDropAdornerLayer.Children.Add(dragDropAdorner);

                        adornerCaptured = e.TouchDevice.Capture(dragDropAdorner);

                        Canvas.SetLeft(dragDropAdorner, initialPoint.X - 20);
                        Canvas.SetTop(dragDropAdorner, initialPoint.Y - 15);

                        dragDropAdornerLayer.PreviewTouchMove += DragDropAdornerLayer_PreviewTouchMove;
                        dragDropAdornerLayer.PreviewTouchUp += DragDropAdornerLayer_PreviewTouchUp;
                    }
                }
            }
        }

        private void DragSource_PreviewTouchUp(object sender, TouchEventArgs e)
        {
            if (!Skip(e.OriginalSource as Visual))
            {
                Clear();
            }
        }

        private void DownSetup(object sender, Visual visual, object e)
        {
            try
            {
                topWindow = (UserControl)DragDropUIHelper.FindAncestor(typeof(UserControl), visual);

                if (e is MouseButtonEventArgs)
                {
                    initialPoint = (e as MouseButtonEventArgs).GetPosition(topWindow);
                }
                else
                {
                    initialPoint = (e as TouchEventArgs).GetTouchPoint(topWindow).Position;
                }

                if (topWindow != null)
                {
                    dragDropAdornerLayer = topWindow.FindName(GetAdornerLayer(sender as DependencyObject)) as Canvas;
                    selectedTarget = topWindow.FindName(GetDropTarget(sender as DependencyObject)) as DataGrid;
                }
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("DownSetup Exception: {0}", exception.Message));
            }
        }

        private void Down(object sender, Point selectedTargetPoint)
        {
            DataGridRow row = DragDropUIHelper.TryFindFromPoint<DataGridRow>((UIElement)sender, selectedTargetPoint);

            if (row == null)
            {
                return;
            }

            selectedRow = row;
            dragData = row.Item;
            dragDataIndex = row.GetIndex();
        }

        private void DragDropAdornerLayer_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            DragDropAdornerLayerMove(e.GetPosition(selectedTarget), e.GetPosition(topWindow));
        }

        private void DragDropAdornerLayer_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            DragDropAdornerLayerUp();
        }

        private void DragDropAdornerLayer_PreviewTouchMove(object sender, TouchEventArgs e)
        {
            DragDropAdornerLayerMove(e.GetTouchPoint(selectedTarget).Position, e.GetTouchPoint(topWindow).Position);
        }

        private void DragDropAdornerLayer_PreviewTouchUp(object sender, TouchEventArgs e)
        {
            DragDropAdornerLayerUp();
        }

        private void DragDropAdornerLayerMove(Point selectedTargetPoint, Point currentPoint)
        {
            DataGridRow row = DragDropUIHelper.TryFindFromPoint<DataGridRow>(selectedTarget, selectedTargetPoint);

            if (row != null)
            {
                selectedTarget.SelectedItem = row.Item;
                dropTarget = row.Item;
                dropTargetIndex = row.GetIndex();
            }
            else
            {
                dropTarget = null;
            }

            currentPoint.X = currentPoint.X - 20;
            currentPoint.Y = currentPoint.Y - 15;

            delta = new Point(initialPoint.X - currentPoint.X, initialPoint.Y - currentPoint.Y);
            scrollTarget = new Point(initialPoint.X - delta.X, initialPoint.Y - delta.Y);

            Canvas.SetLeft(dragDropAdorner, scrollTarget.X);
            Canvas.SetTop(dragDropAdorner, scrollTarget.Y);

            dragDropAdorner.AdornerDropState = DropState.CannotDrop;

            if (dropTarget != null)
            {
                dragDropAdorner.AdornerDropState = DropState.CanDrop;
            }
        }

        private void DragDropAdornerLayerUp()
        {
            if (dragDropAdorner != null)
            {
                switch (dragDropAdorner.AdornerDropState)
                {
                    case DropState.CanDrop:
                        CanDropAnimation();
                        break;
                    case DropState.CannotDrop:
                        CannotDropAnimation();
                        break;
                }
            }

            Clear();
            dragDropAdornerLayer.PreviewMouseMove -= DragDropAdornerLayer_PreviewMouseMove;
            dragDropAdornerLayer.PreviewMouseUp -= DragDropAdornerLayer_PreviewMouseUp;
            dragDropAdornerLayer.PreviewTouchMove -= DragDropAdornerLayer_PreviewTouchMove;
            dragDropAdornerLayer.PreviewTouchUp -= DragDropAdornerLayer_PreviewTouchUp;
        }

        private void CanDropAnimation()
        {
            try
            {
                Storyboard dragDropAdornerStoryboard = dragDropAdorner.Resources["canDrop"] as Storyboard;
                dragDropAdornerStoryboard.Completed += (s, args) =>
                {
                    dragDropAdornerLayer.Children.Clear();
                    dragDropAdornerLayer.Visibility = Visibility.Collapsed;
                };

                dragDropAdornerStoryboard.Begin(dragDropAdorner);

                if (ItemDropped == null)
                {
                    return;
                }

                if (!Equals(dragData, dropTarget))
                {
                    ItemDropped(dragDropAdorner, new DragDropEventArgs(dragData, dropTarget, dragDataIndex, dropTargetIndex));
                }
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("CanDropAnimation Exception: {0}", exception));
            }
        }

        private void CannotDropAnimation()
        {
            try
            {
                Storyboard dragDropAdornerStoryboard = dragDropAdorner.Resources["cannotDrop"] as Storyboard;

                DoubleAnimation aniX = dragDropAdornerStoryboard.Children[0] as DoubleAnimation;
                DoubleAnimation aniY = dragDropAdornerStoryboard.Children[1] as DoubleAnimation;
                aniX.To = delta.X;
                aniY.To = delta.Y;

                dragDropAdornerStoryboard.Completed += (s, args) =>
                {
                    dragDropAdornerLayer.Children.Clear();
                    dragDropAdornerLayer.Visibility = Visibility.Collapsed;
                };

                dragDropAdornerStoryboard.Begin(dragDropAdorner);
            }
            catch (Exception exception)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("CannotDropAnimation Exception: {0}", exception));
            }
        }

        private void Clear()
        {
            if (dragDropAdorner != null)
            {
                dragDropAdorner.ReleaseMouseCapture();
                dragDropAdorner.ReleaseAllTouchCaptures();
            }

            dragData = null;
            adornerCaptured = false;
        }

        private bool Skip(Visual visual)
        {
            if (visual is Button || visual is ComboBox || visual is Image)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public enum DropState
    {
        CanDrop = 1,
        CannotDrop = 2
    }

    public class DragDropEventArgs : EventArgs
    {
        public object DragData;
        public object TargetData;
        public int DragDataIndex;
        public int TargetDataIndex;

        public DragDropEventArgs()
        {

        }

        public DragDropEventArgs(object dragData, object targetData, int dragDataIndex, int targetDataIndex)
        {
            DragData = dragData;
            TargetData = targetData;
            DragDataIndex = dragDataIndex;
            TargetDataIndex = targetDataIndex;
        }
    }

    public class DragDropAdornerBase : UserControl
    {
        public DropState AdornerDropState
        {
            get { return (DropState)GetValue(AdornerDropStateProperty); }
            set { SetValue(AdornerDropStateProperty, value); }
        }

        public static readonly DependencyProperty AdornerDropStateProperty = DependencyProperty.Register("AdornerDropState", typeof(DropState), typeof(DragDropAdornerBase));
    }

    public static class DragDropUIHelper
    {
        public static T TryFindParent<T>(DependencyObject child) where T : DependencyObject
        {
            DependencyObject parentObject = GetParentObject(child);

            if (parentObject == null)
            {
                return null;
            }

            T parent = parentObject as T;

            if (parent != null)
            {
                return parent;
            }
            else
            {
                return TryFindParent<T>(parentObject);
            }
        }

        public static DependencyObject GetParentObject(DependencyObject child)
        {
            if (child == null)
            {
                return null;
            }

            ContentElement contentElement = child as ContentElement;

            if (contentElement != null)
            {
                DependencyObject parent = ContentOperations.GetParent(contentElement);
                if (parent != null)
                {
                    return parent;
                }
                FrameworkContentElement fce = contentElement as FrameworkContentElement;
                return fce != null ? fce.Parent : null;
            }

            return VisualTreeHelper.GetParent(child);
        }

        public static void UpdateBindingSources(DependencyObject obj, params DependencyProperty[] properties)
        {
            foreach (DependencyProperty depProperty in properties)
            {
                BindingExpression be = BindingOperations.GetBindingExpression(obj, depProperty);
                if (be != null)
                {
                    be.UpdateSource();
                }
            }

            int count = VisualTreeHelper.GetChildrenCount(obj);

            for (int i = 0; i < count; i++)
            {
                DependencyObject childObject = VisualTreeHelper.GetChild(obj, i);
                UpdateBindingSources(childObject, properties);
            }
        }

        public static T TryFindFromPoint<T>(UIElement reference, Point point) where T : DependencyObject
        {
            DependencyObject element = reference.InputHitTest(point) as DependencyObject;

            if (element == null)
            {
                return null;
            }
            else if (element is T)
            {
                return (T)element;
            }
            else
            {
                return TryFindParent<T>(element);
            }
        }

        public static FrameworkElement FindAncestor(Type ancestorType, Visual visual)
        {
            while (visual != null && !ancestorType.IsInstanceOfType(visual))
            {
                visual = (Visual)VisualTreeHelper.GetParent(visual);
            }
            return visual as FrameworkElement;
        }

        public static bool IsMovementBigEnough(Point initialMousePosition, Point currentPosition)
        {
            return (Math.Abs(currentPosition.X - initialMousePosition.X) >= SystemParameters.MinimumHorizontalDragDistance || Math.Abs(currentPosition.Y - initialMousePosition.Y) >= SystemParameters.MinimumVerticalDragDistance);
        }
    }
}






How to validate / block double byte int value (Microsoft Japanese IME)

$
0
0
Hi, how to validate / block user input the double byte value (Microsoft Japanese IME keyboard)  in text box ?
Reproduce steps:
1. Add JP keyboard
2. Input value into text box, 10
3. Switch to JP keyboard, mouse highlight value 10 in text box and mouse 2, you will able to see some options to replace the input value into double byte value.
Will upload mini sample soon.


WPF animation: how to animation reverse scan?

$
0
0

Our WPF application needs a animation to show the deck checking progress which includes two parts.

1) A big progress bar which scan back forth (from left to right and then from right to Left).

2) Arc with number percentage to indicate from 0 to 100%.

We have created customized DeckCheckAnaimationView as following:

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

namespace ConsoleApplication.Views
{
    /// <summary>
    /// Interaction logic for DeckCheckAnimationView.xaml
    /// </summary>
    public partial class DeckCheckAnimationView : UserControl
    {
        public DeckCheckAnimationView()
        {
            InitializeComponent();
        }

        #region Dependency Properties
        private static readonly DependencyProperty ProgressWidthIndicatorProperty = DependencyProperty.Register(
          "ProgressWidthIndicator", typeof(double), typeof(DeckCheckAnimationView), new PropertyMetadata(50.0));

        [Category("Common Properties")]
        public double ProgressWidthIndicator
        {
            get { return (double)GetValue(ProgressWidthIndicatorProperty); }
            set { SetValue(ProgressWidthIndicatorProperty, value); }
        }

        private static readonly DependencyProperty ArcPercentageProperty = DependencyProperty.Register(
          "ArcPercentage", typeof(double), typeof(DeckCheckAnimationView), new PropertyMetadata(50.0));

        [Category("Common Properties")]
        public double ArcPercentage
        {
            get { return (double)GetValue(ArcPercentageProperty); }
            set { SetValue(ArcPercentageProperty, value); }
        }

        //in seconds
        private static readonly DependencyProperty TotalDeckCheckTimeProperty = DependencyProperty.Register(
          "TotalDeckCheckTime", typeof(int), typeof(DeckCheckAnimationView), new PropertyMetadata(100));

        [Category("Common Properties")]
        public int TotalDeckCheckTime
        {
            get { return (int)GetValue(TotalDeckCheckTimeProperty); }
            set { SetValue(TotalDeckCheckTimeProperty, value); }
        }

        private static readonly DependencyProperty TotalProgressWidthProperty = DependencyProperty.Register(
          "TotalProgressWidth", typeof(double), typeof(DeckCheckAnimationView), new PropertyMetadata(1000.0));

        [Category("Common Properties")]
        public double TotalProgressWidth
        {
            get { return (double)GetValue(TotalProgressWidthProperty); }
            set { SetValue(TotalProgressWidthProperty, value); }
        }

        private static readonly DependencyProperty IsAbortProperty = DependencyProperty.Register(
          "IsAbort", typeof(bool), typeof(DeckCheckAnimationView), new PropertyMetadata(false));

        public bool IsAbort
        {
            get { return (bool)GetValue(IsAbortProperty); }
            set { SetValue(IsAbortProperty, value); }
        }

        private static readonly DependencyProperty IsStartTimerProperty = DependencyProperty.Register(
          "IsStartTimer", typeof(bool), typeof(DeckCheckAnimationView), new PropertyMetadata(false, IsStartTimerChangedCallback));

        private static void IsStartTimerChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DeckCheckAnimationView _this = d as DeckCheckAnimationView;
            if (_this != null)
            {
                if (e.NewValue != null)
                {
                    if ((bool)e.NewValue)
                    {
                        _this.StartDeckCheckTimer();
                    }
                    else
                        _this.StopDeckCheckTimer();
                }
            }
        }

        public bool IsStartTimer
        {
            get { return (bool)GetValue(IsStartTimerProperty); }
            set { SetValue(IsStartTimerProperty, value); }
        }


        private static readonly DependencyProperty DeckCheckFinishBorderVisibilityProperty = DependencyProperty.Register(
          "DeckCheckFinishBorderVisibility", typeof(Visibility), typeof(DeckCheckAnimationView), new PropertyMetadata(Visibility.Collapsed));

        public Visibility DeckCheckFinishBorderVisibility
        {
            get { return (Visibility)GetValue(DeckCheckFinishBorderVisibilityProperty); }
            set { SetValue(DeckCheckFinishBorderVisibilityProperty, value); }
        }
        #endregion

        #region Timer
        DispatcherTimer _deckCheckTimer;
        double _deckCheckWidthIncreaseUnit = 100.0;
        double _deckCheckArcIncreaseUnit = 1.0;

        public void StartDeckCheckTimer()
        {
            DeckCheckFinishBorderVisibility = Visibility.Collapsed;
            //start Weekly Flush Timer
            if (_deckCheckTimer == null)
            {
                _deckCheckTimer = new DispatcherTimer();
                _deckCheckTimer.Interval = TimeSpan.FromSeconds(1);
                _deckCheckTimer.Tick += new EventHandler(_deckCheckTimer_Tick);
            }
            this.borderDeckChecking.CornerRadius = new CornerRadius(20,0,0,20);
            //_deckCheckWidthIncreaseUnit = (double)(TotalProgressWidth/TotalDeckCheckTime);
            _deckCheckArcIncreaseUnit = ((double)100/TotalDeckCheckTime);
            ProgressWidthIndicator = _deckCheckWidthIncreaseUnit;
            ArcPercentage = _deckCheckArcIncreaseUnit;

            if (_deckCheckTimer != null && !_deckCheckTimer.IsEnabled)
                _deckCheckTimer.Start();
        }

        private void _deckCheckTimer_Tick(object sender, EventArgs e)
        {
            if (TotalProgressWidth - ProgressWidthIndicator > 0.0)
            {
                ProgressWidthIndicator += _deckCheckWidthIncreaseUnit;
            }
            else
            {

            }

            if (100 - ArcPercentage > 0.0)
                ArcPercentage += _deckCheckArcIncreaseUnit;
            else
                StopDeckCheckTimer();
        }

        public void StopDeckCheckTimer()
        {
            DeckCheckFinishBorderVisibility = Visibility.Visible;

            this.borderDeckChecking.CornerRadius = new CornerRadius(20);
            //ProgressWidthIndicator = TotalProgressWidth;
            borderDeckChecking.Width = 0;
            ArcPercentage = 100;

            if (_deckCheckTimer != null && _deckCheckTimer.IsEnabled)
            {
                _deckCheckTimer.Stop();
                _deckCheckTimer = null;
            }
        }
        #endregion
    }
}
using System;

namespace CommonControls
{
    public class ProgressToAngleConverter: System.Windows.Data.IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            double progress = (double)values[0];
            System.Windows.Controls.ProgressBar bar = values[1] as System.Windows.Controls.ProgressBar;

            return 359.999 * (progress / (bar.Maximum - bar.Minimum));
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
<UserControl x:Class="AppliedBioCode.BioCode3000.ConsoleApplication.Views.DeckCheckAnimationView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:controls="clr-namespace:AppliedBioCode.BioCode3000.CommonControls;assembly=CommonControls"
             xmlns:converters="clr-namespace:AppliedBioCode.BioCode3000.ConsoleApplication.Converters"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             x:Name="DeckCheckAnimation"><Grid Background="Transparent"><Grid.Resources><LinearGradientBrush  x:Key="ProgressBarForegroundDeckCheck"><GradientStop Color="White" Offset="0"/><GradientStop Color="LightYellow" Offset=".5"/><GradientStop Color="#ffff2a" Offset="1"/></LinearGradientBrush><LinearGradientBrush  x:Key="ProgressBarForegroundDeckCheckReverse"><GradientStop Color="#f2ff2a" Offset="0"/><GradientStop Color="LightYellow" Offset=".5"/><GradientStop Color="White" Offset="1"/></LinearGradientBrush><sys:Double x:Key="DeckCheckBackgroundOpacity">.7</sys:Double><!--progress bar style for deck checking--><controls:ProgressToAngleConverter x:Key="ProgressConverter"/><Style TargetType="{x:Type ProgressBar}" x:Key="DeckCheckProgressBarStyle"><Setter Property="Width" Value="320"/><Setter Property="Height" Value="320"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ProgressBar}"><Grid><!--<Ellipse Stroke="Black" Fill="{TemplateBinding Background}"/><Ellipse Stroke="Black" Margin="40" Fill="White"/>--><!--<controls:ArcControl StrokeThickness="30" Stroke="{TemplateBinding BorderBrush}" Margin="5">--><controls:ArcControl StrokeThickness="30" Stroke="White" Margin="5"><controls:ArcControl.StartAngle><MultiBinding Converter="{StaticResource ProgressConverter}"><Binding Path="Minimum" RelativeSource="{RelativeSource TemplatedParent}"/><Binding Path="." RelativeSource="{RelativeSource TemplatedParent}"/></MultiBinding></controls:ArcControl.StartAngle><controls:ArcControl.EndAngle><MultiBinding Converter="{StaticResource ProgressConverter}"><Binding Path="Value" RelativeSource="{RelativeSource TemplatedParent}"/><Binding Path="." RelativeSource="{RelativeSource TemplatedParent}"/></MultiBinding></controls:ArcControl.EndAngle><controls:ArcControl.Effect><DropShadowEffect Opacity=".4"/></controls:ArcControl.Effect></controls:ArcControl><StackPanel Orientation="Horizontal"
                                                    Margin="30"
                                                    HorizontalAlignment="Center"><TextBlock Text="{Binding Value, RelativeSource={RelativeSource TemplatedParent}, StringFormat=\{0:0\}}"
                                                Foreground="White"
                                                VerticalAlignment="Center"
                                                HorizontalAlignment="Center"
                                                FontSize="100" FontWeight="Normal"/><TextBlock Text="%"
                                                Foreground="White"
                                                VerticalAlignment="Center"
                                                HorizontalAlignment="Center"
                                                FontSize="70" FontWeight="Normal"/></StackPanel></Grid></ControlTemplate></Setter.Value></Setter></Style></Grid.Resources><Border x:Name="borderDeckChecking"
                Width="0"
                HorizontalAlignment="Left"
                VerticalAlignment="Stretch"
                Background="{StaticResource ProgressBarForegroundDeckCheck}"
                Opacity="{StaticResource DeckCheckBackgroundOpacity}"
                CornerRadius="20"
                RenderTransformOrigin="0.5,0.5"><Border.Resources><Style TargetType="{x:Type Border}"><Setter Property="LayoutTransform"><Setter.Value><ScaleTransform/></Setter.Value></Setter><Style.Triggers><DataTrigger Binding="{Binding Path=IsStartTimer, ElementName=DeckCheckAnimation}" Value="True"><DataTrigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetProperty="Width" From="0" To="1000" Duration="0:0:10" RepeatBehavior="Forever" AutoReverse="True"/><!--<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleX" From="1" To="-1" Duration="0:0:.1" BeginTime="0:0:3" />--></Storyboard></BeginStoryboard></DataTrigger.EnterActions><DataTrigger.ExitActions><BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetProperty="Width" To="0" Duration="0:0:.1"/><!--<DoubleAnimation Storyboard.TargetName="borderDeckChecking2" Storyboard.TargetProperty="Width" To="0" Duration="0:0:.1"/>--></Storyboard></BeginStoryboard></DataTrigger.ExitActions></DataTrigger></Style.Triggers></Style></Border.Resources></Border><!--<Border x:Name="borderDeckChecking2"
                Width="0"
                HorizontalAlignment="Left"
                VerticalAlignment="Stretch"
                Background="{StaticResource ProgressBarForegroundDeckCheckReverse}"
                Opacity="{StaticResource DeckCheckBackgroundOpacity}"
                CornerRadius="20"></Border>--><Border x:Name="borderDeckCheckingFinish"
                Background="Green"
                Opacity=".3"
                CornerRadius="20"
                Visibility="{Binding DeckCheckFinishBorderVisibility, ElementName=DeckCheckAnimation}"/><Grid VerticalAlignment="Center"><ProgressBar x:Name="circleProgressBarStatus"
                         Style="{StaticResource DeckCheckProgressBarStyle}"
                         Value="{Binding ArcPercentage, Mode=TwoWay, ElementName=DeckCheckAnimation}"
                         Panel.ZIndex="200"/></Grid></Grid></UserControl>
<View:DeckCheckAnimationView
                Grid.Row="1"
                Margin="10,5,10,10"
                Visibility="{Binding WFDeckcheckViewVisibility}"
                IsStartTimer="{Binding IsDeckCheckAnimation}"
                TotalDeckCheckTime="{Binding TotalDeckCheckTime}"></View:DeckCheckAnimationView>

For A big progress bar which scans back forth (from left to right and then from left to right), we animate Border.Width from Left to Right by setting Border.Width from 0 to 1000. So far, when scan back, it just reverse the scan forth.

<DataTrigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetProperty="Width" From="0" To="1000" Duration="0:0:10" RepeatBehavior="Forever" AutoReverse="True"/><!--<DoubleAnimation Storyboard.TargetProperty="LayoutTransform.ScaleX" From="1" To="-1" Duration="0:0:.1" BeginTime="0:0:3" />--></Storyboard></BeginStoryboard></DataTrigger.EnterActions>

What we really want to is when scanning back, it reverses the progress bar, so the progress bar is scan from right to left.

We do not know which Border property we should animate to achieve this goal. The reason we use Border control is the progress bar has to match with background which

CornerRadius

="20"

Does anyone has idea which Border property we should animate to achieve this goal?

Or should we use different control for animation? Thx!

  


JaneC



Best way to wait

$
0
0

I have a WPF app A that launches a process B.  When B is getting launched, I start playing a WPF animation.  A and B communicate with some IPC.  When B has completed initialization it sends an event to A notifying it that it is initialized. At this point, I want the WPF app A to do something provided the transition animation is _also_ completed.  If it is not complete, I want to wait until it is.  A simple way (but maybe not elegant) is like this:

public void OnEvent(Event data) // ProcessB init complete
{
    while(!IsLaunchTransitionComplete) { Thread.Sleep(100); }

    DoSomething();
}

Is there a better way?

wpf listview column colors

$
0
0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            lsvOrder.Items.Add(new ListViewData("1", "0001", "T1", "Timer1", "Timer4"));
            lsvOrder.Items.Add(new ListViewData("2", "0002", "T2", "Timer2", "Timer5"));
            lsvOrder.Items.Add(new ListViewData("3", "0003", "T3", "Timer3", "Timer6"));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }

    public class ListViewData
    {
        public ListViewData(string col1, string col2, string col3, string col4, string col5)
        {
            NUMBER = col1;
            ORDER = col2;
            TABLE = col3;
            ORDER_TIMER = col4;
            TABLE_TIMER = col5;
        }

        public string NUMBER { get; set; }
        public string ORDER { get; set; }
        public string TABLE { get; set; }
        public string ORDER_TIMER { get; set; }
        public string TABLE_TIMER { get; set; }
    }

    public class RowColourConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            ListViewItem item = (ListViewItem)value;
            ListView lv = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
            int index = lv.ItemContainerGenerator.IndexFromContainer(item);
            if (index % 2 == 0)
            {
                return Brushes.Black;//my table
            }
            return Brushes.White;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

<Window x:Class="WpfApplication1.MainWindow"
xmlns:local="clr-namespace:WpfApplication1"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="452" Width="614"><Grid x:Name="gridHome" HorizontalAlignment="Left" Height="300" Margin="0,10,-52,-318" VerticalAlignment="Top" Width="600"><ListView x:Name="lsvOrder" Height="300" Margin="0,10,0,-10" VerticalAlignment="Top"><ListView.Resources><local:RowColourConverter x:Key="RowColourConverter"/><Style TargetType="ListViewItem"><Setter Property="Background"><Setter.Value><Binding RelativeSource="{RelativeSource Self}"
                              Converter="{StaticResource RowColourConverter}"/></Setter.Value></Setter></Style></ListView.Resources><ListView.View><GridView><GridViewColumn Header="No" Width="60"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding NUMBER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Order No" Width="120"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding ORDER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="table" Width="120" ><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding TABLE}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Order Info" Width="150"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding ORDER_TIMER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Table Info" Width="150"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding TABLE_TIMER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn></GridView></ListView.View></ListView><Button Content="Button" HorizontalAlignment="Left" Height="65" Margin="20,329,0,-94" VerticalAlignment="Top" Width="75" Click="Button_Click"/></Grid></Window>

I want to display the background color ofeach column.

How can I do this?

Pleasehelp.


listview column colours setting

$
0
0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
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 WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            lsvOrder.Items.Add(new ListViewData("1", "0001", "T1", "Timer1", "Timer4"));
            lsvOrder.Items.Add(new ListViewData("2", "0002", "T2", "Timer2", "Timer5"));
            lsvOrder.Items.Add(new ListViewData("3", "0003", "T3", "Timer3", "Timer6"));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }

    public class ListViewData
    {
        public ListViewData(string col1, string col2, string col3, string col4, string col5)
        {
            NUMBER = col1;
            ORDER = col2;
            TABLE = col3;
            ORDER_TIMER = col4;
            TABLE_TIMER = col5;
        }

        public string NUMBER { get; set; }
        public string ORDER { get; set; }
        public string TABLE { get; set; }
        public string ORDER_TIMER { get; set; }
        public string TABLE_TIMER { get; set; }
    }

    public class RowColourConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            ListViewItem item = (ListViewItem)value;
            ListView lv = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
            int index = lv.ItemContainerGenerator.IndexFromContainer(item);
            if (index % 2 == 0)
            {
                return Brushes.Black;//my table
            }
            return Brushes.White;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

<Window x:Class="WpfApplication1.MainWindow"
xmlns:local="clr-namespace:WpfApplication1"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="452" Width="614"><Grid x:Name="gridHome" HorizontalAlignment="Left" Height="300" Margin="0,10,-52,-318" VerticalAlignment="Top" Width="600"><ListView x:Name="lsvOrder" Height="300" Margin="0,10,0,-10" VerticalAlignment="Top"><ListView.Resources><!--<local:RowColourConverter x:Key="RowColourConverter"/>
                <Style TargetType="ListViewItem">
                    <Setter Property="Background">
                        <Setter.Value>
                            <Binding RelativeSource="{RelativeSource Self}"
                              Converter="{StaticResource RowColourConverter}"/>
                        </Setter.Value>
                    </Setter>
                </Style>-->
</ListView.Resources><ListView.View><GridView><GridViewColumn Header="No" Width="60"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding NUMBER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Order No" Width="120"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding ORDER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="table" Width="120" ><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding TABLE}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Order Info" Width="150"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding ORDER_TIMER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Table Info" Width="150"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding TABLE_TIMER}" ></TextBlock></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn></GridView></ListView.View></ListView><Button Content="Button" HorizontalAlignment="Left" Height="65" Margin="20,329,0,-94" VerticalAlignment="Top" Width="75" Click="Button_Click"/></Grid></Window>

I would like to set alternating background column.

<GridBackground="Pink"> <-alternating Colours(from programming code setting)


Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>