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

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"?


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

$
0
0
Hi, how to validate / block user input the 0 - 100 double byte value (Japanese keyboard)  in text box ?

How to use a MVVM for the user control plus the MVVM of the main control?

$
0
0

I ahve a main view in my application that has this XAML:

<local:ucMyControlView Grid.Column="1" HorizontalAlignment="Left" Margin="5,77,0,0" VerticalAlignment="Top"
		MyProperySelectedItem="{Binding MyPropertyInViewModelSelectedItem, Mode=TwoWay}"/>

And I have this propery in my view model of the main control:

private MyType _myPropertyInViewModelSelectedItem;
public int MyPropertyInViewModelSelectedItem
{
	get { return _myPropertyInViewModelSelectedItem; }
	set
	{
		_myPropertyInViewModelSelectedItem = value;
		base.RaisePropertyChangedEvent("MyPropertyInViewModelSelectedItem");
	}
}

Now the user control that I want to use in the main user control. The XAML is this:

<UserControl x:Class="MyApplication.Views.ucMySecondUserControlView"
        Height="Auto" Width="Auto" ><UserControl.DataContext><vm:ucMySecondUserControlViewModel /></UserControl.DataContext><Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><ComboBox Height="23" HorizontalAlignment="Left" Margin="0,25,0,0" Name="cmbTipos" VerticalAlignment="Top" Width="120" Grid.Column="0"
                ItemsSource="{x:Static vg:Items1}"
                SelectedItem="{Binding SelectedItem1, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=local:ucMySecondUserControlView}}"></ComboBox><ComboBox Height="23" HorizontalAlignment="Left" Margin="4,25,0,0" Name="cmbClases" VerticalAlignment="Top" Width="120"
				ItemsSource="{x:Static vg:Items2}"
				SelectedItem="{Binding SelectedItem2, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=local:ucMySecondUserControlView}}"></ComboBox></Grid></UserControl>

The view model that I want to use with this second user control:

private MyType _selectedItem1;
public MyType SelectedItem1
{
	get { return _selectedItem1; }
	set
	{
		_selectedItem1 = value;
		base.RaisePropertyChangedEvent("SelectedItem1");
	}
}

private MyType2 _selectedItem2;
public MyType2 SelectedItem2
{
	get { return _selectedItem2; }
	set
	{
		_selectedItem2 = value;
		base.RaisePropertyChangedEvent("SelectedItem2");
	}
}

But the set of the SelectedItem1 is not rised.

Really what I want to do is this. I have a main usr control that use this second user control. When I select an intem in the first comboBox in the second user control, I want, in the view model of the main user control, rise the set of the property that binds the property of the second user control. But also I want when I select an item in the first comboBox, that the set of the propery SelectedItem1 is raised to set later the items that the second comboBox has to have, because depends on the selection of the first comboBox.

This is a general and simple example to learn, beacause really what I want to do is this, when I select a intem in a second user control, to be notify in the main view model to some work and also to be notify in the view model of the second user control because the control has its internal logic too.

Thanks.

How to create a user control to be reused in many projects with MVVM and not expose the view model class to main application?

$
0
0

I come from here post

In sumary, i have a user control that I want to reuse in many projects, and this user control has a view model because I would like to use the MVVM pattern. I want that when I change a value in a comboBox in this user control, notify to the view model of the main application the change, because the main application has to do something when the value changes. Also, the user control has its own logic, so I have to do something in the view model of the user control when the selected item in the comboBox it is changed.

Well, the solutions that, 1 and 2 needs that the main view model has access to the view model class of the user control. I would like avoid this because I would like to have a more easier to use user control, just only I want to bind the depedency property and nothing more.

The 3 option it is to use events, but it seems that it is for communicate view models, so I guess that the main view model needs to have access to the view model class of the user control.

So my question is, is it possible to implement a user control with MVVM pattern in which I just need to bind dependency properties?

Thanks.

WPF word alignment issues while MaxTextWidth is set

$
0
0

I am using FormattedText to display text. I need to align the text horizontally as per options provided. Everything works fine till I set the "MaxTextWidth" property(I need this for word trimming). How do I align the text along with word trimming enabled?

        FormattedText formatted_text = new FormattedText(
                text, System.Globalization.CultureInfo.GetCultureInfo("en-US"),
                FlowDirection.LeftToRight,
                typeface, em_size, brush);
       formatted_text.TextAlignment = TextAlignment.Right;
       drawingContext.DrawText(formatted_text, origin);

This works fine aligning the code as expected. But I need to trim the word w.r.t MaxTextWidth. I run into issues in setting MaxTextWidth. How do I calculate MaxTextWidth?

The point in the image is the origin.


The above is the properly aligned image when I do not set the MaxTextWidth.



And I lose the alignment when I set MaxTextWidth.

Please guide, TIA.

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 apply style to Listbox Item based on Property value in WPF

$
0
0

Hi,
<ListBox
ItemsSource="{Binding Customers}"><ListBox.ItemTemplate><DataTemplate><GridMargin="1"x:Name="BackgroundGrid"><TextBlockText="{Binding CustomerName}"/><TextBlockText="{Binding CustomerId}"/></Grid><DataTemplate.Triggers><DataTriggerBinding="{Binding CustomerId}"Value="9-3453"><SetterTargetName="BackgroundGrid"Property="Background"Value="Red"/></DataTrigger></DataTemplate.Triggers></DataTemplate></ListBox.ItemTemplate></ListBox>

In the above code, I need to provide DataTrigger's value based on property value instead of hard code the value.

Thanks in advance

How to Increase the mouse scrolling sensitivity on the listings Page.

$
0
0

I have code  for left and  right scrolling by the mouse wheeler. Code

 private void sv_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            ScrollViewer scrollviewer = sender as ScrollViewer;
            if (e.Delta > 0)
                scrollviewer.LineLeft();
            else
                scrollviewer.LineRight();
            e.Handled = true;
        }

now We want to  increase the speed of  mouse wheeler. How to possible?

Please provide need full help.

thanks in advance

Ankit



How to apply style on several storyboards

$
0
0

Hello, 

For this question I have looked all over the internet trying to find a solid answer, but wasn't just there. 

I have the following [several] storyboards setup. Just like this. 

<Window.Resources><Storyboard x:Key="Storyboard1" ><DoubleAnimationUsingPath
                Duration="0:0:3"

                Completed="MyStoryboardCompleted"
                Source="X"
                Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
                 Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M1.5,-18.667014 L8.1669813,-54.00002 L31.833186,-94.666719 L60.166999,-116.33299"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath><DoubleAnimationUsingPath
                Duration="0:0:3"
                Completed="MyStoryboardCompleted"
                Source="Y"
                Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
                Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M1.5,-18.667014 L8.1669813,-54.00002 L31.833186,-94.666719 L60.166999,-116.33299"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath></Storyboard><Storyboard x:Key="Storyboard2"><DoubleAnimationUsingPath
                Duration="0:0:3"
                Source="X"
                Completed="Timeline_OnCompleted"
                Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)"
                Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M62.25,-115.75 L110,-134 L149,-129 L172.25,-122"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath><DoubleAnimationUsingPath
                Duration="0:0:3"
                Source="Y"
                Completed="Timeline_OnCompleted"
                Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)"
                Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M62.25,-115.75 L110,-134 L149,-129 L172.25,-122"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath></Storyboard><Storyboard x:Key="Storyboard3"><DoubleAnimationUsingPath Name="path3" Duration="0:0:2" Source="X" Completed="Timeline_OnCompleted4" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M177.75,-120.25 L197.75,-105.75 L217.5,-87.75 L235.25,-70.25"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath><DoubleAnimationUsingPath Duration="0:0:2" Source="Y"  Completed="Timeline_OnCompleted4" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M177.75,-120.25 L197.75,-105.75 L217.5,-87.75 L235.25,-70.25"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath></Storyboard><Storyboard x:Key="Storyboard4"><DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="ObjectToMove"><EasingDoubleKeyFrame KeyTime="0" Value="3.5"/></DoubleAnimationUsingKeyFrames><DoubleAnimationUsingPath Duration="0:0:2" Source="X" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry ><PathGeometry   Figures="M238.75,-64.08299 L301.58333,-64 L323.25,-64"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath><DoubleAnimationUsingPath Duration="0:0:2" Source="Y" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="ObjectToMove"><DoubleAnimationUsingPath.PathGeometry><PathGeometry Figures="M238.75,-64.08299 L301.58333,-64 L323.25,-64"/></DoubleAnimationUsingPath.PathGeometry></DoubleAnimationUsingPath></Storyboard></Window.Resources><Window.Triggers><EventTrigger RoutedEvent="FrameworkElement.Loaded"><BeginStoryboard Storyboard="{StaticResource Storyboard1}"/></EventTrigger></Window.Triggers>

And in same xaml file i have the rectangle like so. 

<Rectangle x:Name="ObjectToMove" Height="31" Canvas.Left="-316.5" Stroke="Black" Canvas.Top="431.5" Width="42" Fill="#FFDA6C11" RenderTransformOrigin="0.5,0.5"><Rectangle.RenderTransform><TransformGroup><ScaleTransform/><SkewTransform/><RotateTransform/><TranslateTransform/></TransformGroup></Rectangle.RenderTransform></Rectangle>

What I am trying to achieve is for some of us pretty simple, but being a new to wpf makes things little bit hard. 

What I am trying to do is have the targetname setup dynamically instead of having them statically, this so that I can have more than 1 object  use the same storyboards.

I heard that style might do the job. And so I looked everywhere but wasn't able to find anything similar.  Could someone please help out. Thanks so much. 

wpf Busy Indicator is not showing up when followed by Application.Current.Dispatcher.BeginInvoke code

$
0
0

I am using wpf busy indicator and setting its Isbusy property from viewModel. After setting Isbusy property  I want to filter my ICollectionview and push it on UI. This Filter operation I have put in

<br></br><br>IsBusy= true;</rb>
   
<br>await

        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new

System.Action(() =>
</br>
                  
<br>{</br>
                     
<br> this.MyCollectionView.Filter = item =></br>
                     
<br> {</br>
                       
<br>   Iitem IdName = item as Iitem;</br>
                       
<br>   return Regex.IsMatch(IdName.Name, SearchText, RegexOptions.IgnoreCase);</br>
                 
<br>     };</br>
               
<br>   }));</br>


Workaround: If I put Task.Delay(200).Wait(); after setting IsBusy, busy indicator will be displayed for some cases.

Please help! Thanks

Busy Cursor

$
0
0

Hello,

I want to create a windows 8 like busy cursor using wpf. Can someone please point me to a solution or atleast an approach for implementing this?

Currently my busy cursor stops or does not work when I call the long running operation.

Regards,

Amarnath Katti

WPF datagrid background

$
0
0
I would like to see the grid background using predefined theme.

Creating a World Map

$
0
0

Hello,

I need to create or rather draw a World map using wpf and then display the flight traffic. I do not want to use bing maps or any third party map controls. How do I accomplish this?

I want to draw a raw map on screen using geographical coordinates for land and sea.

Regards,

Amarnath Katti

column templatization wpf gridcontrol

$
0
0

how can I get my desired column templatization using column Template property?

Dependency / Attached Properties in WPF

$
0
0

Hi

I have four Buttons (Add, Update, Delete and search with respective Ico(Images.png)). I have created each and every button style and do content binding and Image source. Each button style is different or I need to inherit style due to every button have different ImageSource. Is it possible to create  only one style for all button with attached or dependency property?

I don't know how to use Dependency and Attached property. I am first time using this. 

My Code:

public class TextblockExtension:Control
    {

 public static ImageSource GetImageSource(DependencyObject obj)
        {
            return (ImageSource)obj.GetValue(ImageSourceProperty);
        }

        public static void SetImageSource(DependencyObject obj, ImageSource ImagePath)
        {
            obj.SetValue(ImageSourceProperty, ImagePath);
        }

        public static readonly DependencyProperty ImageSourceProperty =
            DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(TextblockExtension));

}

IN Xaml:

            

<StackPanel Orientation="Vertical" Height="320" VerticalAlignment="Bottom" Grid.Column="1">
            <Button Content="Save" Width="100" Grid.Column="0" Grid.Row="0" Height="30" Margin="4" Template="{DynamicResource SaveButtonControlTemplate1}"
                    local:TextblockExtension.ImageSource="Images/save.png"/>
            <Button Content="Update" Width="70" Grid.Column="1" Grid.Row="0" Height="30" Margin="4"/>
            <Button Content="Delete" Width="70" Grid.Column="2" Grid.Row="0" Height="30" Margin="4"/>
            <Button Content="Search" Width="70" Grid.Column="3" Grid.Row="0" Height="30" Margin="4"/>

        </StackPanel>

and in ControlTemplate of Button :

<ControlTemplate x:Key="SaveButtonControlTemplate1" TargetType="{x:Type Button}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="50"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Image Grid.Column="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
                <TextBlock Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Text="{TemplateBinding Content}" Padding="5,5,0,0"/>
            </Grid>
        </ControlTemplate>


How to get the last selected item in WPF Datagrid

$
0
0

I am using a WPF Datagrid and I want to keep a record of which was the last selected item when I do selection changed event but want to cancel the operation if user opts for the same.

For this I used eventargs travel from my Veiw to Viewmodel. Is there any other way ? I wanted to do it in pure MVVM fashion. Relevant code below

<i:Interaction.Triggers>                       

<i:EventTrigger EventName="SelectionChanged">                           

<cal:ActionMessage MethodName="grd_SelectionChanged"  >

<cal:Parameter Value="$eventArgs"/>                        

</cal:ActionMessage>
                     
</i:EventTrigger>

</i:Interaction.Triggers>

In the view model in the event handler

publicasyncvoidgrd_SelectionChanged(SelectionChangedEventArgseventArgs)

{

var previousElement = eventArgs.RemovedItems[0] as ISomeIdName;
                    if (previousElement != null)
                    {
                        SomeIdName = previousElement;
                    }

}

Dragging image from User control is firing Window leave event on WPF Mainwindow

$
0
0

Hi,

  I am using multiple user control inside my main window( I am using ribbon window) , if i start dragging from one of the user control main window mouse leave, mouse move events will hit, which is not supposed to happen and after execution it wont fire at all (mouse move and mouse leave should hit). I want event to fire when mouse pointer on dragging when it goes out of main window. Please help me out in understanding the concept and work around it.

Regards

Harsha D


Harsha Bhat

Get items from ICollection

$
0
0

Hi,

How can I get items from ICollection? I have Two ListViews with Multiselect mode. 

Listview_01:

- ItemsSource is bind to an ObservableCollection from EF

ItemsSource="{Binding EmployeeViewM.MainActivity}"

- SelectionMode = "Multiple"

- Limit to selected items set to 2.

<i:Interaction.Behaviors><listv:ListViewSelectedItemBehavior SelectedItems="{Binding EmployeeViewM.SelectedAll, Mode=TwoWay}"/><limit:LimitSelectionBehavior Limit="2"/></i:Interaction.Behaviors>

- SelectedItems (attached property) is bind to ICollection with Mode = "TwoWay"

Private _selectedAll As ICollection(Of Object)

Public Property SelectedAll() As ICollection(Of Object)
            Get
                Return _selectedAll
            End Get
            Set(value As ICollection(Of Object))
                _selectedAll = value
                RaisePropertyChanged("SelectedAll")
            End Set
        End Property

ListView_02:

- ItemsSource is bind to SelectedAll property from ListView_01 (SelectedItems)

ItemsSource="{Binding EmployeeViewM.SelectedAll}"

- SelectionMode = "Multiple"

- SelectedItems is also bind to SelectedAll ICollection with Mode = "OneWayToSource"

When I select items from the ListView_01 they will appear in ListView_02. ListView_01 is used to to start the calculation for the items, so I need to get the columns, names etc from the ICollection to save it in the database (.SaveChanges with EF). ListView_02 is used to present current activity time for each item. When I select item on ListView_02 it should get current selected item and close it - update record already saved in the database by ListView_01. To do this I need items from ICollection.

I was trying to do this with IsSelected property:

Public ReadOnly Property SelectedActivities() As IEnumerable(Of Object)
            Get
                Return SelectedAll.Where(Function(o) o.IsSelected)
            End Get
        End Property

Public Property IsSelected() As Boolean
            Get
                Return m_IsSelected
            End Get
            Set
                m_IsSelected = Value
            End Set
        End Property
        Private m_IsSelected As Boolean

But I get an exception:

Public member 'IsSelected' on type 'tbl_Activity_Activit_3020B3967BDD1C526BE47639551D058532416104E5B71FD569BF8119EA5ED3D4' not found.

Thank you for any suggestions

Disable Virtual keyboard for a given Text Field on Windows 8 tablet

$
0
0

Dear experts,

 

For one of my developments, when the user clicks on a button, it opens a new screen with a focus on a text field.

If I correctly understand, it is a standard behavior that the virtual keyboard is displayed when focusing on a text field. However, since this field will be populated using a barcode scanner (manual input using the keyboard is still an option but not the preferred one) I would like to keep the keyboard hidden when focusing on this field. 

 

In the open UI code, I cannot really see how and where I could achieve this. Please also take into account that I want to keep the focus on this specific field, since I want that the user can use it without selecting this field first.

 

Could you please advise on how I should proceed to achieve this?    

 

Many thanks in advance for your feedback!


Compatibility issue with Expression.Blend.Sdk 1.0.2 System.Windows.Interactivity.dll only in Visual Studio 2015

$
0
0

I'm developing a WPF with Visual Studio 2015 Community, C#, .NET Framework 4.6.1, Prism.Wpf 6.1.0, Prism.Core 6.1.0 and Expression.Blend.Sdk 1.0.2.

I'm following: Implement a confirmation dialog in WPF using MVVM and Prism tutorial.

I have added Interaction triggers to a Windows.xaml:

<Window x:Class="MyProject.Views.MainWindow"
            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"
            xmlns:local="clr-namespace:MyProject.Helpers"
            xmlns:ViewModel="clr-namespace:MyProject.ViewModels"
            xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
            mc:Ignorable="d"
            Title="MainWindow" Height="604.62" Width="655.879"><Window.DataContext><ViewModel:MainViewModel/></Window.DataContext><i:Interaction.Triggers><!-- Trigger listening for the "Raised" event on the source object (of type IInteractionRequest) --><i:EventTrigger EventName="Raised" SourceObject="{Binding ConfirmationInteractionRequest}"><i:EventTrigger.Actions><local:StartBatchWindowAction /></i:EventTrigger.Actions></i:EventTrigger></i:Interaction.Triggers><Grid x:Name="MainGrid">

I get the following error on <local:StartBatchWindowAction />:

The type from assembly is built with an older version of blend sdk and  is not supported in a windows presentation foundation 4 project

This is StartBatchWindowAction class:

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

    namespace MyProject.Helpers
    {
        public class StartBatchWindowAction : TriggerAction<FrameworkElement>
        {
            protected override void Invoke(object parameter)
            {
                throw new NotImplementedException();
            }
        }
    }

How can I fix this problem?

I have used ILSpy to check that dll and this is what I got:

// D:\Development\packages\Expression.Blend.Sdk.1.0.2\lib\net45\System.Windows.Interactivity.dll
// System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

// Global type: <Module>
// Architecture: AnyCPU (64-bit preferred)
// Runtime: .NET 4.0

using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Windows.Markup;

[assembly: AssemblyVersion("4.5.0.0")]
[assembly: CLSCompliant(true)]
[assembly: Debuggable]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Windows.Interactivity")]
[assembly: AssemblyFileVersion("3.0.40218.0")]
[assembly: AssemblyProduct("System.Windows.Interactivity")]
[assembly: AssemblyTitle("System.Windows.Interactivity")]
[assembly: NeutralResourcesLanguage]
[assembly: CompilationRelaxations(8)]
[assembly: InternalsVisibleTo("Microsoft.Expression.DesignSurface.UnitTests, PublicKey=...")]
[assembly: InternalsVisibleTo("Microsoft.Expression.BlendSDK.UnitTests, PublicKey=...")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: ComVisible(false)]
[assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = "")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/expression/2010/interactivity", "System.Windows.Interactivity")]
[assembly: XmlnsPrefix("http://schemas.microsoft.com/expression/2010/interactivity", "i")]
[assembly: SecurityPermission(8, SkipVerification = true)]
[module: UnverifiableCode]

I think this issue has been reported to Microsoft: https://connect.microsoft.com/VisualStudio/feedback/details/755407/xaml-designer-will-not-display-when-using-blend-sdk-behaviors#

And also there is a thread talking about this problem on Prism: https://github.com/PrismLibrary/Prism/issues/213


You can find project source here: https://github.com/VansFannel/WpfApplicationModalWindow
Viewing all 18858 articles
Browse latest View live