Visualizzazione post con etichetta "wpf". Mostra tutti i post
Visualizzazione post con etichetta "wpf". Mostra tutti i post

domenica 8 settembre 2013

Implementare INotifyPropertyChanged

Di seguito viene illustrato come implementare l'interfaccia INotifyPropertyChanged per notificare che una proprietà è cambiata.
public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
 
        if (handler != null)
        {
            handler(thisnew PropertyChangedEventArgs(propertyName));
        }
    }
 
    private string miaProprieta;
    public string MiaProprieta
    {
        get { return miaProprieta; }
        set 
        {
            if (miaProprieta != value)
            {
                miaProprieta = value;
                OnPropertyChanged("MiaProprieta");
            }
        }
    }
}

sabato 27 luglio 2013

[WPF-SL-Win8] Modern UI (Metro) Charts per Windows 8, WPF, Silverlight

Progetto open source che ci pemette di creare dei grafici in stile metro nella applicazione per Windows 8, WPF e Silverlight.

Grafici disponibili

  • ColumnChart (ClusteredColumnChart, StackedColumnChart, StackedColumnChart100Percent)
  • PieChart (PieChart and Dognut)
  • BarChart (ClusteredBarChart, StackedBarChart, StackedBarChart100Percent)
  • Doughnut Chart
  • Radial Gauge Chart
E' possibile visualizzare un esempio in Silverlight al seguente link

Sito ufficiale

lunedì 22 luglio 2013

[WPF] Command

I Command vengono utilizzati per evitare di assegnare un determinato comportamento direttamente al controllo e per riutilizzare semplicemente le funzionalità di un'applicazione.
Esempio su come utilizzarli:

C#

public MainWindow()
{
    InitializeComponent();
}
 
private void Comando_CanExecute(object senderCanExecuteRoutedEventArgs e)
{
    //Condizione per determinare se eseguire o meno il comando
    e.CanExecute = textBox1.Text == "ok";
    e.Handled = true;
}
 
private void Comando_Execute(object senderExecutedRoutedEventArgs e)
{
    e.Handled = true;
    MessageBox.Show("Command in WPF");
}

XMAL

<Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Command in WPF" Height="184.831" Width="346.723">
    <Window.Resources>
        <RoutedUICommand x:Key="Comando" />
    </Window.Resources>
    <Window.CommandBindings>
        <CommandBinding Command="{StaticResource Comando}" CanExecute="Comando_CanExecute" Executed="Comando_Execute" />
    </Window.CommandBindings>
    <Grid>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="10,23,0,0" TextWrapping="Wrap" Name="textBox1" VerticalAlignment="Top" Width="120"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="149,23,0,0" VerticalAlignment="Top" Width="75" Command="{StaticResource Comando}"/>
    </Grid>
</Window>


martedì 16 luglio 2013

[WPF] ContextMenu DataGridRow

Ecco come creare un ContextMenu per DataGridRow:

<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="Nuovo" VCommand="{StaticResource nuovo}">
                            <MenuItem.Icon>
                                <Image Source="/Images/nuovo.png" Height="24"/>
                            </MenuItem.Icon>
                        </MenuItem>
                        <MenuItem Header="Elimina" Command="{StaticResource elimina}">
                            <MenuItem.Icon>
                                <Image Source="/Images/elimina.png" Height="24"/>
                            </MenuItem.Icon>
                        </MenuItem>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

martedì 9 luglio 2013

[WPF] Modern UI for WPF

Modern UI for WPF è un insieme di controlli e stili (open source) che ci consente di creare delle interfacce grafiche in stile Metro.

Elenco delle funzionalità:

  • Temi dark, ligh e personalizzabili (configurabile a runtime)
  • Controlli
    • BBCodeBlock
    • ModernButton
    • ModernDialog
    • ModernFrame
    • ModernMenu
    • ModernTab
    • ModernWindow
    • RelativeAnimatingContentControl
    • TransitioningContentControl
  • Layout
  • Stili controlli
  • Template di progetto (Visual Studio 2012)
Sito ufficiale

sabato 6 luglio 2013

[WPF] Extended WPF Toolkit

Extended WPF Toolkit è una racconta di controlli da utilizzare nei progetti WPF.


Versioni disponibili:
La versione Open Source (2.0) include i seguenti controlli:
  • AvalonDock 
  • AutoSelectTextBox
  • BusyIndicator
  • ButtonSpinner
  • Calculator
  • CalculatorUpDown
  • CheckComboBox
  • CheckListBox
  • ChildWindow
  • CollectionEditor
  • DataGrid
  • CollectionControlDialog
  • ColorCanvas
  • ColorPicker
  • DateTimePicker
  • DateTimeUpDown
  • DecimalUpDown
  • DoubleUpDown
  • DropDownButton
  • IntegerUpDown
  • Magnifier
  • MaskedTextBox
  • MessageBox
  • MultiLineTextEditor
  • Pie
  • PrimitiveTypeCollEditor
  • PropertyGrid
  • RichTextBox
  • RichTextBoxFormatBar
  • SplitButton
  • Panels/Layouts
    • SwitchPanel
    • WrapPanel
    • RandomPanel
  • TimelinePanel
  • TimePicker
  • WatermarkTextBox
  • WindowContainer
  • WindowControl
  • Windows 8 Theme
  • Wizard
  • Zoombox
Sito ufficiale

giovedì 4 luglio 2013

[WPF - SL] Interfaccia multi-finestre con FloatingWindow

FloatingWindow è un'insieme di librerie che permette di creare delle interfacce multi-finestre (multi-windows interface).


E' disponibile sia per WPF che per Silverlight.

  • Struttura

Gli elementi principali presenti nel progetto sono:
  1. FloatingWindow: Classe di base della finestra ridimensionabile (resizable windows)
  2. FloatingWindowHost: Elemento canvas che contiene le varie FloatinWindo
  3. Iconbar: Pannelo contenente le icone della finestra
  4. Bootstrap Button: pulsante di apertura/chiusura dell'IconBar
  5. Bottom Bar: controllo che può hostare altri tipi di controlli
  •  Utilizzo

L'utilizzo è estremamente semplice. Basta creare il "contenitore" di tipo FloatingWindowHost e inserire le varie FloatingWindow.

Creazione FloatingWindowHost da XAML
<my:FloatingWindowHost x:Name="host"
    SnapinEnabled="True" ShowMinimizedOnlyInIconbar="False">
</my:FloatingWindowHost>


Creazione FloatingWindow da C#
FloatingWindow window = new FloatingWindow();
window.Title = "New window";
host.Add(window);
window.Show();


Creazione FloatingWindow da XAML
<my:FloatingWindow x:Class="FloatingWindowControl.DetailsForm"
    xmlns:my="clr-namespace:SilverFlow.Controls;assembly=SilverFlow.Controls"
    Height="Auto" MinWidth="100" MinHeight="100"
    Title="Details" IconText="Details Form" Tag="Details">

sabato 29 giugno 2013

[WPF] Applicazioni in stile metro con MahApps.Metro

MahApps.Metro è un toolkit per creare applicazioni WPF in stile metro.
E' possibile installarlo tramite NuGet:

PM> Install-Package MahApps.Metro

oppure scaricare i sorgenti direttamente dal repository ufficiale

  

Il toolkit comprende i seguenti controlli:
  • MetroWindow
  • Panorama
  • Buttons
    • Standard Button
    • MetroCircleButton
    • Square button
    • FlatButton
  •  Toggle Switch
  •  TextBox
  • Progress Ring
  • AnimatedTabControl
  • AnimatedSingleRowTabControl
  • Range Slider
  • TransitioningContentControl
MahApps.Metro non iclude i file di risorse. Tuttavia è possibile installarle tramite NuGet:

PM> Install-Package MahApps.Metro.Resources
Sito ufficiale

giovedì 27 giugno 2013

[WPF] Ottenere la TextBox inserita nella ComboBox

public static TextBox getTextBox(ComboBox combo)
{
    return combo.Template.FindName("PART_EditableTextBox"comboas TextBox;
}

mercoledì 26 giugno 2013

[WPF] Caricare un'immagine a runtime

Ecco come caricare un'immagine a runtime:

public void LoadImage(string path)
{
    BitmapImage bmp = new BitmapImage();
    bmp.BeginInit();
    bmp.UriSource = new Uri(pathUriKind.RelativeOrAbsolute);
    bmp.EndInit();
 
    img.Source = bmp;
}

martedì 25 giugno 2013

[WPF] Utilizzare controlli WinForms in WPF

Per integrare nei progetti WPF dei controli WinForms ci viene in aiuto la classe WindowsFormHost di WindowsFormIntegration.dll
<Window x:Class="EsempioWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="401.124" Width="792.416">
    <Grid>
        <WindowsFormsHost Margin="0">
            <xxx:TuoControlloWinForms x:Name="controlloWinForm"/>
        </WindowsFormsHost>
    </Grid>
</Window>

lunedì 24 giugno 2013

[WPF] PasswordBox e DataBinding

Nativamente la passwordbox non consente si effettuare il databinding perché la proprità Password non è una di tipo DependencyProperty. Per ovviare a ciò non ci resta che creare la classe di supporto PasswordHelper:

public static class PasswordHelper
    {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password",
            typeof(string), typeof(PasswordHelper),
            new FrameworkPropertyMetadata(string.EmptyOnPasswordPropertyChanged));
 
        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach",
            typeof(bool), typeof(PasswordHelper), new PropertyMetadata(falseAttach));
 
        private static readonly DependencyProperty IsUpdatingProperty =
           DependencyProperty.RegisterAttached("IsUpdating"typeof(bool),
           typeof(PasswordHelper));
 
 
        public static void SetAttach(DependencyObject dpbool value)
        {
            dp.SetValue(AttachPropertyvalue);
        }
 
        public static bool GetAttach(DependencyObject dp)
        {
            return (bool)dp.GetValue(AttachProperty);
        }
 
        public static string GetPassword(DependencyObject dp)
        {
            return (string)dp.GetValue(PasswordProperty);
        }
 
        public static void SetPassword(DependencyObject dpstring value)
        {
            dp.SetValue(PasswordPropertyvalue);
        }
 
        private static bool GetIsUpdating(DependencyObject dp)
        {
            return (bool)dp.GetValue(IsUpdatingProperty);
        }
 
        private static void SetIsUpdating(DependencyObject dpbool value)
        {
            dp.SetValue(IsUpdatingPropertyvalue);
        }
 
        private static void OnPasswordPropertyChanged(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            passwordBox.PasswordChanged -= PasswordChanged;
 
            if (!(bool)GetIsUpdating(passwordBox))
            {
                passwordBox.Password = (string)e.NewValue;
            }
            passwordBox.PasswordChanged += PasswordChanged;
        }
 
        private static void Attach(DependencyObject sender,
            DependencyPropertyChangedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
 
            if (passwordBox == null)
                return;
 
            if ((bool)e.OldValue)
            {
                passwordBox.PasswordChanged -= PasswordChanged;
            }
 
            if ((bool)e.NewValue)
            {
                passwordBox.PasswordChanged += PasswordChanged;
            }
        }
 
        private static void PasswordChanged(object senderRoutedEventArgs e)
        {
            PasswordBox passwordBox = sender as PasswordBox;
            SetIsUpdating(passwordBoxtrue);
            SetPassword(passwordBoxpasswordBox.Password);
            SetIsUpdating(passwordBoxfalse);
        }
    }

XAML:
xmlns:helper="clr-namespace:XXX.Utility" 
<PasswordBox helper:PasswordHelper.Attach="True" helper:PasswordHelper.Password="{Binding Password,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" />

venerdì 21 giugno 2013

[WPF] Sfondo di selezione trasparente ListBoxItem

Da incollare nel file App.xaml
<Style x:Key="ListBoxItemStyleTransparentSelect" TargetType="ListBoxItem">
 <Setter Property="Foreground" Value="Black"/>
 <Setter Property="FontSize" Value="10"/>
 <Setter Property="FontFamily" Value="Arial"/>
 <Setter Property="Padding" Value="1"/>
 <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
 <Setter Property="VerticalContentAlignment" Value="Top"/>
 <Setter Property="Background" Value="Transparent"/>
 <Setter Property="BorderThickness" Value="0"/>
 <Setter Property="Template">
  <Setter.Value>
   <ControlTemplate TargetType="ListBoxItem">
    <Grid Background="{TemplateBinding Background}">
     <VisualStateManager.VisualStateGroups>
      <VisualStateGroup x:Name="CommonStates">
       <VisualState x:Name="Normal"/>
       <VisualState x:Name="MouseOver">
        <Storyboard>
         <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="fillColor"/>
        </Storyboard>
       </VisualState>
       <VisualState x:Name="Disabled">
        <Storyboard>
         <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="contentPresenter"/>
        </Storyboard>
       </VisualState>
      </VisualStateGroup>
      <VisualStateGroup x:Name="SelectionStates">
       <VisualState x:Name="Unselected"/>
       <VisualState x:Name="Selected"/>
      </VisualStateGroup>
      <VisualStateGroup x:Name="FocusStates">
       <VisualState x:Name="Focused"/>
       <VisualState x:Name="Unfocused"/>
      </VisualStateGroup>
     </VisualStateManager.VisualStateGroups>
     <Rectangle x:Name="fillColor" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
     <Rectangle x:Name="fillColor2" IsHitTestVisible="False" Opacity="0" RadiusY="1" RadiusX="1"/>
     <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}"/>
     <Rectangle x:Name="FocusVisualElement" RadiusY="1" RadiusX="1" StrokeThickness="1" Visibility="Collapsed"/>
    </Grid>
   </ControlTemplate>
  </Setter.Value>
 </Setter>
</Style>

martedì 18 giugno 2013

[WPF/SL/WP] Clonare ObservableCollection

Metodo esteso che consente di clonare una generica ObservableCollection.
public static ObservableCollection<T> Clone<T> (this ObservableCollection<T> source)
{
    if (source != null)
    {
        var res = new ObservableCollection<T>();
 
        foreach (var item in source)
        {
            res.Add(Clone<T>(item));
        }
        return res;
    }
    return null;
}

lunedì 17 giugno 2013

[WPF] Stile validazione campo TextBox

Da incollare nel file App.xaml

<Style TargetType="{x:Type TextBox}">
                <Setter Property="Validation.ErrorTemplate">
                    <Setter.Value>
                        <ControlTemplate>
                            <DockPanel LastChildFill="True">
                                <TextBlock DockPanel.Dock="Right" Foreground="Gray" Margin="2" FontSize="12pt" Text="*" />
                                <Border >
                                    <AdornedElementPlaceholder Name="MyAdorner" />
                                </Border>
                            </DockPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Style.Triggers>
                    <Trigger Property="Validation.HasError" Value="true">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

[WPF] Binding Radio Button To Enum

Codice per effettuare il binding fra radio button ed un enumeratore
C#
 public class EnumBooleanConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string parameterString = parameter as string;
            if (parameterString == null)
                return DependencyProperty.UnsetValue;
 
            if (System.Enum.IsDefined(value.GetType(), value) == false)
                return DependencyProperty.UnsetValue;
 
            object parameterValue = System.Enum.Parse(value.GetType(), parameterString);
 
            return parameterValue.Equals(value);
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string parameterString = parameter as string;
            if (parameterString == null)
                return DependencyProperty.UnsetValue;
 
            return System.Enum.Parse(targetType, parameterString);
        }
    }
 
XAML
IsChecked="{Binding Enumeratore, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=Valore,UpdateSourceTrigger=PropertyChanged}"/>