Tag Archive for WPF

Bind WPF Window Background to Windows Style

<Window x:Class="HydroSoft.Display.Settings.SerialProvidersWindow"
        xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation"" >http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>
        xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml"" >http://schemas.microsoft.com/winfx/2006/xaml"</a>
        WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow"
        Background="{x:Static SystemColors.ControlBrush}">
</Window>

source

Drag & Drop with WPF in C#

// WPF Canvas Object
// Canvas LayoutCanvas;
//
// Events Required
//
// Canvas_PreviewMouseLeftButtonDown
// Canvas_PreviewMouseMove
// Canvas_PreviewMouseLeftButtonUp
// Parent_PreviewKeyDown
//
// LayoutCanvas.PreviewMouseLeftButtonDown += LayoutCanvas_PreviewMouseLeftButtonDown;
// LayoutCanvas.PreviewMouseMove += LayoutCanvas_PreviewMouseMove;
// LayoutCanvas.PreviewMouseLeftButtonUp += LayoutCanvas_PreviewMouseLeftButtonUp;
// WindowOrPage.PreviewKeyDown += WindowOrPage_PreviewKeyDown;
//
// Parameters Required
//
// For capturing the mouse position:
// Point ddStartPoint;
//
// The top left corner of the child object (left = x, top = y)
// double ddOriginalLeft;
// double ddOriginalTop;
//
// Properties for managing the state of the drag & drop process:
// bool ddIsMouseDown;
// bool ddIsBeingDragged;
//
// Our original UI element (in my case the children are all Image objects)
// UIElement ddOriginalElement;
//
// The container of the above element when we are in dragging mode
// System.Windows.Shapes.Rectangle ddOverlay;
//

//
// Canvas_PreviewMouseLeftButtonDown
//
// We assign this to our Canvas object as it will control
// catching whether or not we are clicking on the canvas itself
// or on one of its children
//
private void LayoutCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    // If the source of the click is our canvas object then we want
    // to exit because we are looking for it's children to drag 
    // and not the canvas itself.
    if(e.Source == LayoutCanvas)
    {
	return;
    }
    
    // Identifies that we have started dragging
    ddIsMouseDown = true;

    // Captures the mouse position in the layout canvas
    ddStartPoint = e.GetPosition(LayoutCanvas);

    // Sets up our element that we will be dragging
    ddOriginalElement = (UIElement)e.Source;

    // Tells the Window to give the mouse to the LayoutCanvas
    // object.
    LayoutCanvas.CaptureMouse();

    e.Handled = true;
}	

//
// Canvas_PreviewMouseMove
// 
// Our event handler for updating the position of our
// dragged element
//
// This introduces two helper methods DragStarted() and DragMoved()
// They will be covered later on in the code.
//
private void LayoutCanvas_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
    if(ddIsMouseDown)
    {
	if(!ddIsBeingDragged)
	{
	    // Capture our mouse position relative to the LayoutCanvas object
	    var mousePosition = e.GetPosition(LayoutCanvas);

	    // Creates a transparent rectangle around our current drag point and we want to 
	    // check here that we are within that rectangle
	    if(Math.Abs(mousePosition.X - ddStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance &&
		    Math.Abs(mousePosition.Y - ddStartPoint.Y) > SystemParameters.MinimumVeritcalDragDistance)
	    {
		DragStarted();
	    }
	}
	else
	{
	    DragMoved();
	}
    }
}

//
// Canvas_PreviewMouseLeftButtonUp
//
// Controls the functionality for finishing our drag and drop process.
// This will also introduce the call to DragFinished(bool state);
//
private void LayoutCanvas_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // This is a fairly simple check. If we are still dragging
    // or starting to drag which means ddIsMouseDown would be 'True'
    // then we don't stop the drag
    if(ddIsMouseDown)
    {
	DragFinished(false);
    }
}

//
// Page_PreviewKeydown
//
// In my code I have my canvas in a Page, you can do this with a Window object as well.
//
private void Page_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
    if(e.Key == Key.Escape && ddIsBeingDragged)
    {
	DragFinished = true;
    }
}

// Helper Methods

//
// DragStarted()
//
//
private void DragStarted()
{
    // Capture our last remaining properties
    // needed to support our drag and drop
    // process
    ddIsBeingDragged = true;
    ddOriginalLeft = Canvas.GetLeft(ddOriginalElement);
    ddOriginalTop = Canvas.GetTop(ddOriginalElement);

    // What we are doing here is creating a semi-transparent
    // mirror image of the object we are dragging.
    //
    // This allows us to visually see that we have selected 
    // an object and are dragging it.
    var brush = new VisualBrush(ddOriginalElement);
    brush.Opacity = 0.5;

    ddOverlay = new System.Windows.Shapes.Rectangle();
    ddOverlay.Width = ddOriginalElement.RenderSize.Width;
    ddOverlay.Height = ddOriginalElement.RenderSize.Height;
    ddOverlay.Fill = brush;

    // Finally add the overlay to the LayoutCanvas for displaying
    LayoutCanvas.Children.Add(ddOverlay);
}


//
// DragMoved();
//
private void DragMoved()
{
    // Capture the current mouse position, this will be used
    // to redraw the overlay element we created in DragStarted()
    var currentPosition = System.Windows.Input.Mouse.GetPosition(LayoutCanvas);
    var elementLeft = (currentPosition.X - ddStartPoint.X) + ddOriginalLeft;
    var elementTop = (currentPosition.Y - ddStartPoint.Y) + ddOriginalTop;

    // We update the overlay's position on the LayoutCanvas
    // by setting it's top left corner position below
    Canvas.SetLeft(ddOverlay, elementLeft);
    Canvas.SetTop(ddOverlay, elementTop);
}

//
// DragFinished();
//
private void DragFinished(bool canceled)
{
    if(ddOverlay != null)
    {
	// capture our current position
	var topLeft = Canvas.GetLeft(ddOverlay);
	var top = Canvas.GetTop(ddOverlay);

	if(ddIsBeingDragged)
	{
	    LayoutCanvas.Children.Remove(ddOverlay);

	    // If it wasn't prematurely canceled, then
	    // move the element to the current mouse position
	    if(!canceled)
	    {
		Canvas.SetLeft(ddOriginalElement, topLeft);
		Canvas.SetTop(ddOriginalElement, top);
	    }

	    // Release the mouse from the layoutcanvas.
	    // This is very important. If you do not release the mouse
	    // you have to set the focus of the mouse to another application
	    // and then back again to regain mouse control
	    LayoutCanvas.ReleaseMouseCapture();

	    // Reset our drag & drop properties
	    ddOverlay = null;
	    ddIsMouseBeingDragged = false;
	    ddIsMouseDown = false;
	}
    }
}

source

WPF DataBinding

<StackPanel>
        <StackPanel.Resources>
            <XmlDataProvider x:Key="MoreColors" XPath="/colors">
                <x:XData>
                    <colors >
                        <color name="pink"/>
                        <color name="white"/>
                        <color name="black"/>
                        <color name="cyan"/>
                        <color name="gray"/>
                        <color name="magenta"/>
                    </colors>
                </x:XData>
            </XmlDataProvider>

        </StackPanel.Resources>
        <ListBox x:Name="lbColor" Width="248" Height="56" 
    IsSynchronizedWithCurrentItem="True" 
    ItemsSource="{Binding Source={StaticResource MoreColors}, 
    XPath=color/@name}">
        </ListBox>
    </StackPanel>

source

WPF XAML Ressources

<UserControl.Resources>
<Style x:Key="{x:Type ComboBox}" TargetType="ComboBox">
<Style TargetType="{x:Type TabControl}" />

<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/PVStyles;component/PVStyles.xaml" />
<ResourceDictionary Source="ExpanderResource.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>

<!-- ExpanderResource.xaml --!>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:igDP="http://infragistics.com/DataPresenter"
xmlns:igRibbon="http://infragistics.com/Ribbon"
xmlns:igEditors="http://infragistics.com/Editors"
xmlns:igWindows="http://infragistics.com/Windows"
xmlns:igThemes="http://infragistics.com/Themes"
xmlns:igDock="http://infragistics.com/DockManager"
xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<LinearGradientBrush x:Key="DarkBrush" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Color="#FF6DACC8" Offset="0.0"/>
<GradientStop Color="#FF6DACC8" Offset="1.0"/>
</GradientStopCollection>
</GradientBrush.GradientStops>
</LinearGradientBrush>

<Style TargetType="Expander" />
</ResourceDictionary>

source

RelayCommand class

public class RelayCommand : ICommand
{
#region Fields

readonly Action<object> _execute;
readonly Predicate<object> _canExecute;

#endregion // Fields

#region Constructors

public RelayCommand(Action<object> execute)
: this(execute, null)
{
}

public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");

_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors

#region ICommand Members

[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}

public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}

public void Execute(object parameter)
{
_execute(parameter);
}

#endregion // ICommand Members
}

// To use this class within your viewmodel class:
RelayCommand _myCommand;
public ICommand MyCommand
{
get
{
if (_myCommand == null)
{
_myCommand = new RelayCommand(p => this.DoMyCommand(p),
p => this.CanDoMyCommand(p) );
}
return _myCommand;
}
}

source

ViewModelBase class

public class ViewModelBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members

public event PropertyChangedEventHandler PropertyChanged;

public void NotifyChanged(string propertyName)
{
if (string.IsNullOrEmpty(propertyName))
throw new ArgumentNullException("propertyName");

if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgspropertyName));
}

#endregion
}

source

Manipulate GUI from another Thread

private void Button_Click(object sender, RoutedEventArgs e)
{
Thread t= new Thread(new ThreadStart(tuwas));
t.Start();
}

public  void tuwas()
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
{
myStackPanel.Children.Add(new Button());
}));
}

source

Table Cell Borders in XAML

<UserControl x:Class="MultidimensionalViews.Views.ColoredBarCellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Grid.Column="4" Grid.Row="3" Width="100" Height="100">
<Grid>
<Rectangle Fill="Transparent" Stroke="Black" StrokeDashCap="Square" StrokeThickness="2" />
<StackPanel Orientation="Vertical" Name="stackPanel" Margin="2" />
</Grid>
</UserControl>

source

WPF Colors

Random r = new Random();
byte[] argb = new byte[4];
r.NextBytes(argb);
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(argb[0], argb[1], argb[2], argb[3]);

source

DataBinding with procedural Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPF_Testground
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
BindingSource bindingSource = new BindingSource();
public Window1()
{
InitializeComponent();
createTextBlock();
}

public void createTextBlock()
{

BindingSource bindingSource2 = new BindingSource();

TextBlock tb = new TextBlock();
tb.Text = "Eine Box";
Binding binding = new Binding();
binding.Source = bindingSource;
binding.Path = new PropertyPath("Wert");
tb.SetBinding(TextBlock.TextProperty, binding);
grid.Children.Add(tb);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
bindingSource.Wert++;
}

}

class BindingSource : System.Windows.DependencyObject
{
public static System.Windows.DependencyProperty WertProperty;

public BindingSource()
{
if (BindingSource.WertProperty == null)
{
BindingSource.WertProperty = System.Windows.DependencyProperty.Register("Wert", typeof(int), typeof(BindingSource));
}
SetValue(BindingSource.WertProperty, 0);
}

public int Wert
{
get { return Int32.Parse(GetValue(BindingSource.WertProperty).ToString()); }
set { SetValue(BindingSource.WertProperty, value); }
}
}
}

source