Showing posts with label wpf. Show all posts
Showing posts with label wpf. Show all posts

MVVM WPF

mouse move event command http://www.codeproject.com/Tips/478643/Mouse-Event-Commands-for-MVVM

C# Обработываем событие на Hotkey в приложениях WPF

Способ 1

        public MainWindow()
        {
            InitializeComponent();
            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
        }

        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
            {
                MessageBox.Show("CTRL + SHIFT + TAB trapped");
            }

            if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                MessageBox.Show("CTRL + TAB trapped");
            }
        }



Способ 2

<Window x:Class="WPFHotkey.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPFHotkey"
        Title="MainWindow" Height="350" Width="525">
    <Window.CommandBindings>
        <CommandBinding Command="local:MainWindow.Some_Command" Executed="Some_Executed"/>
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="F4" Modifiers="ALT" Command="local:MainWindow.Some_Command"/>
    </Window.InputBindings>
    <Grid>
        
    </Grid>
</Window>


using System.Windows;
using System.Windows.Input;

namespace WPFHotkey
{
    
    public partial class MainWindow : Window
    {
        public static RoutedCommand Some_Command = new RoutedCommand();


        private void Some_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Hi!");
        }

        public MainWindow()
        {
            InitializeComponent();
        }

    }
}

C# How to change UI control from other thread (WinForms and WPF)

WinForms:
public delegate void updateTextBoxDelegate(String textBoxString);  
public updateTextBoxDelegate updateTextBox; 

void updateTextBox1(string str ) { textBox1.Text = str1; } 

void display( string strItem ) 
{
         Form1.Invoke( Form1.updateTextBox, strItem ); 
}


WPF:
tempWindow.Dispatcher.BeginInvoke(new Action(delegate()
                    {
tempWindow.ChangeControlMethod();
                    }));

C# Локализация Windows 8 приложений


Введение

Шаблоны Windows Phone 8 проектов теперь включают в себя поддержку локализаций приложений. Что такое локализация? Когда вы разрабатываете приложение Windows Phone app, часто вам необходимо это делать сразу  для нескольких регионов и соответственно нескольких языков, простыми словами вам необходимо перевести интерфейс или какую то графическую часть. 

Давайте создадим Windows Phone 8 приложение и на примере посмотрим как локализовать его.

Первым делом нам вам необходимо выбрать "Windows Phone OS 8.0" платформу когда создаете свое приложение.

Step 1: Создадим новое Windows Phone 8 приложение с целевой платформой версии 8.0.

Как я говорил локализация доступна для восьмой версии платформы; она не поддерживается в версии 7.1, вы можете увидеть различия между версиями на картинке ниже, когда вы создаете Windows Phone 8.0 приложение файл ресурсов находится в папке "Resources" для каждой поддерживаемой локализации и создается класс "LocalizedStrings", также используется привязка с помощью XAML.

windowsphone8-localization1.gif

По умолчанию запись, относящаяся к  классу помощнику "LocalizedStrings" создается в файле App.xaml.

windowsphone8-localization2.gif

Шаг 2: Теперь давайте привяжем заголовок приложения к свойству из global resource.
 
<!--TitlePanel contains the name of the application and page title-->
 
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
 
     <TextBlock Text="{Binding Path=LocalizedResources.ApplicationTitle}" 
                 
 Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
 
     <TextBlock Text="{Binding Path=LocalizedResources.MainPageTitle}" Margin="9,-7,0,0"
 
                 Style="{StaticResource PhoneTextTitle1Style}"/>
 
</StackPanel>

Посмотрим на функцию 
 InitializeLanguage():

windowsphone8-localization3.gif

Шаг 3: Добавим определенную локализацию приложения.

Зайдите в свойства проекта и там вы можете выбрать язык который желаете использовать.

windowsphone8-localization4.gif

После добавления новых языков создадутся соответствующие файлы ресурсов и добавятся в папку Resources.

windowsphone8-localization5.gif

Все файлы ресурсов содержат все детали локализации, чтобы их посмотреть нам не обязательно запускать приложение.

Когда вы откроете файл Resources.resx вы увидите ApplicationTitle на разных языках.

windowsphone8-localization6a.gif

windowsphone8-localization7a.gif

Step 4: Протестируем наше приложением просто запустив эмулятор и мы увидим ApplicationTitle на главной странице по умолчанию.

windowsphone8-localization13.gif

Теперь давайте протестируем нашу новую локализацию.

Для изменения языка используйте следующий порядок действий.

Шаг 1: Нажмите кнопку Start, потом нажмите на иконку стрелку.

windowsphone8-localization8.gif

Шаг 2: Выберите настройки из списка и нажмите на region & language.

windowsphone8-localization9.gif

windowsphone8-localization10.gif

Шаг 3: Выберите язык который вы добавили. Мы добавили немецкий так что выберем его.

windowsphone8-localization11.gif

windowsphone8-localization12.gif
Шаг 4: Нажмите чтобы подтвердить изменения и перезагрузите телефон.

windowsphone8-localization15.gif

Эмулятор изменит настройки и вернет стартовое окно.

Теперь запустите своё приложение и вы увидите переведенный UI.

windowsphone8-localization14.gif

c# scroll panel with picturebox by dragging mouse


private Point _StartPoint;
void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left)
    _StartPoint = e.Location;
}
void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
  if (e.Button == MouseButtons.Left) {
    Point changePoint = new Point(e.Location.X - _StartPoint.X, 
                                  e.Location.Y - _StartPoint.Y);
    panel1.AutoScrollPosition = new Point(-panel1.AutoScrollPosition.X - changePoint.X,
                                          -panel1.AutoScrollPosition.Y - changePoint.Y);
  }
}
A Meaning (Prod. By Joel Johnston) by Hi-Rez on Grooveshark

c# create image with transparent background / c# Создание изображения с прозрачным бэкграундом

1)Use Bitmap.MakeTransparent()

Bitmap b = new Bitmap(ImageWithNonTransparentBackGround);
b.MakeTransparent(Color.Trasparent);

2)

var image = new Bitmap(135, 135, PixelFormat.Format32bppArgb);
using (var g = Graphics.FromImage(image)) {
g.Clear(Color.Transparent);
g.DrawLine(Pens.Red, 0, 0, 135, 135);
}

textblock wrap text font

Отличный мануал про это и всё другое http://msdn.microsoft.com/en-us/library/cc189010(v=vs.95).aspx

C# WPF Control with transparent background

  1. //Set background color
  2. mycontrol.Background = Brushes.Green;
  3. //Not transparent
  4. mycontrol.Opacity=1;
  5. //Half transparent
  6. mycontrol.Opacity=0.5;

How to add a CheckBox to a Menu Item in WPF

xaml
  1. <MenuItem IsCheckable="True" x:Name="_showSolutionExplorer" Header="Solution Explorer" Click="_showContent_Click"></MenuItem>  

c#
  1. private void _showContent_Click(object sender, RoutedEventArgs e)   
  2. {   
  3.     If ((sender as MenuItem).IsChecked)   
  4.         MessageBox.Show("MenuItem is checked");   
  5.     else   
  6.         MessageBox.Show("MenuItem is not checked");   
  7. }  

c# wpf treeView return list of all nodes / Рекурсивный перебор элементов


  1. private void PrintRecursive(TreeNode treeNode)   
  2. {   
  3.    // Print the node.   
  4.    System.Diagnostics.Debug.WriteLine(treeNode.Text);   
  5.    MessageBox.Show(treeNode.Text);   
  6.    // Print each node recursively.   
  7.    foreach (TreeNode tn in treeNode.Nodes)   
  8.    {   
  9.       PrintRecursive(tn);   
  10.    }   
  11. }   
  12.    
  13. // Call the procedure using the TreeView.   
  14. private void CallRecursive(TreeView treeView)   
  15. {   
  16.    // Print each node recursively.   
  17.    TreeNodeCollection nodes = treeView.Nodes;   
  18.    foreach (TreeNode n in nodes)   
  19.    {   
  20.       PrintRecursive(n);   
  21.    }   
  22. }  

Timer in WPF


  1. private void Window_Loaded(object sender, RoutedEventArgs e)   
  2.    
  3. {   
  4.    
  5.     DispatcherTimer dispatcherTimer = new DispatcherTimer();   
  6.    
  7.     dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);   
  8.    
  9.     dispatcherTimer.Interval = new TimeSpan(0, 0, 1);   
  10.    
  11.     dispatcherTimer.Start();   
  12.    
  13. }   
  14.    
  15.     
  16.    
  17. private void dispatcherTimer_Tick(object sender, EventArgs e)   
  18.    
  19. {   
  20.    
  21.     listBox1.Items.Add(DateTime.Now.Hour.ToString() + ":" +   
  22.    
  23.         DateTime.Now.Second.ToString());   
  24.    
  25.        
  26.    
  27.     CommandManager.InvalidateRequerySuggested();   
  28.    
  29.     listBox1.Items.MoveCurrentToLast();   
  30.    
  31.     listBox1.SelectedItem = listBox1.Items.CurrentItem;   
  32.    
  33.     listBox1.ScrollIntoView(listBox1.Items.CurrentItem);   
  34.    
  35. }  



Multi-coloured code for a blog http://aivolkov.ru/online-syntax-highlighter/

c# WPF Аналог Delphi Application.ProcessMessages и WinForms Application.DoEvents


  1. private void DoEvents()   
  2. {   
  3.     Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));   
  4. }   
  5.   
  6. private void btnDel_Click(object sender, RoutedEventArgs e)   
  7. {   
  8.     popupLoad.IsOpen = true;   
  9.     DoEvents();   
  10.     if (eDelRecord != null)   
  11.         eDelRecord(this, EventArgs.Empty);   
  12.     popupLoad.IsOpen = false;   
  13. }  

c# WPF oval button

  1. <ControlTemplate x:Key="myButton" TargetType="Button">   
  2.     <Grid Width="{TemplateBinding ActualWidth}"   
  3.             Height="{TemplateBinding ActualHeight}" Background="#00FFFFFF">   
  4.         <Ellipse Name="Circle" StrokeThickness="1">   
  5.             <Ellipse.Fill>   
  6.                 <LinearGradientBrush EndPoint="2.2,0" StartPoint="0,0">   
  7.                     <LinearGradientBrush.GradientStops>   
  8.                         <GradientStop Offset="0" Color="LightGray" />   
  9.                         <GradientStop Offset="0.3" Color="Gray" />   
  10.                     </LinearGradientBrush.GradientStops>   
  11.                 </LinearGradientBrush>   
  12.             </Ellipse.Fill>   
  13.         </Ellipse>   
  14.         <ContentPresenter x:Name="content" HorizontalAlignment="Center" VerticalAlignment="Center"/>   
  15.     </Grid>   
  16.     <ControlTemplate.Triggers>   
  17.         <Trigger Property="UIElement.IsEnabled" Value="false">   
  18.             <Setter Property="Shape.Fill" TargetName="Circle">   
  19.                 <Setter.Value>   
  20.                     <LinearGradientBrush EndPoint="2.2,0" StartPoint="0,0">   
  21.                         <LinearGradientBrush.GradientStops>   
  22.                             <GradientStop Offset="0" Color="#FFFFFFFF" />   
  23.                             <GradientStop Offset="0.5" Color="#FFEBEEF5" />   
  24.                             <GradientStop Offset="0.5" Color="#FFD8DDEB" />   
  25.                             <GradientStop Offset="1" Color="#FFDFE2F0" />   
  26.                         </LinearGradientBrush.GradientStops>   
  27.                     </LinearGradientBrush>   
  28.                 </Setter.Value>   
  29.             </Setter>   
  30.         </Trigger>   
  31.         <Trigger Property="UIElement.IsMouseOver" Value="true">   
  32.             <Setter Property="Shape.Fill" TargetName="Circle">   
  33.                 <Setter.Value>   
  34.                     <LinearGradientBrush EndPoint="2.2,0" StartPoint="0,0">   
  35.                         <LinearGradientBrush.GradientStops>   
  36.                             <GradientStop Offset="0" Color="#FFFFFFFF" />   
  37.                             <GradientStop Offset="0.1" Color="#FFDFEDF9" />   
  38.                             <GradientStop Offset="0.47" Color="#FF3086E1" />   
  39.                             <GradientStop Offset="0.47" Color="#FF003B91" />   
  40.                             <GradientStop Offset="0.7" Color="#FF1793EF" />   
  41.                             <GradientStop Offset="0.85" Color="#FF5AD4FF" />   
  42.                             <GradientStop Offset="0.95" Color="#FFBDFFFF" />   
  43.                             <GradientStop Offset="1" Color="#FFFFFFFF" />   
  44.                         </LinearGradientBrush.GradientStops>   
  45.                     </LinearGradientBrush>   
  46.                 </Setter.Value>   
  47.             </Setter>   
  48.         </Trigger>   
  49.         <Trigger Property="ButtonBase.IsPressed" Value="True">   
  50.             <Setter Property="Shape.Fill" TargetName="Circle">   
  51.                 <Setter.Value>   
  52.                     <LinearGradientBrush EndPoint="2.2,0" StartPoint="0,0">   
  53.                         <LinearGradientBrush.GradientStops>   
  54.                             <GradientStop Offset="0" Color="#FFC0D2F5" />   
  55.                             <GradientStop Offset="0.47" Color="#FF5E7A9C" />   
  56.                             <GradientStop Offset="0.47" Color="#FF00062D" />   
  57.                             <GradientStop Offset="0.7" Color="#FF005F9F" />   
  58.                             <GradientStop Offset="0.85" Color="#FF1FA4E2" />   
  59.                             <GradientStop Offset="0.95" Color="#FF61DAFF" />   
  60.                             <GradientStop Offset="1" Color="#FF48CFFF" />   
  61.                         </LinearGradientBrush.GradientStops>   
  62.                     </LinearGradientBrush>   
  63.                 </Setter.Value>   
  64.             </Setter>   
  65.         </Trigger>   
  66.     </ControlTemplate.Triggers>   
  67. </ControlTemplate>   

Result:


No action


IsMouseOver


IsPressed