Tuesday, September 3, 2019

[Code snippet] INotifyPropertyChanged in the model and subscribed the PropertyChanged event of the model in ViewModel

Be The First To Comment
internal class Model:INotifyPropertyChanged
    {
        public Model()
        {
        }

        string _FirstName = "Shahir";
        public string FirstName
        {
            get { return _FirstName; }
            set
            {
                _FirstName = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if(PropertyChanged!=null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


internal class MyViewModel:INotifyPropertyChanged
    {
        private Model myModel;

        public MyViewModel(Model model)
        {
            this.myModel = model;
            myModel.PropertyChanged += myModel_PropertyChanged;
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        string _FirstName;
        public string MyFirstName
        {
            get { return myModel.FirstName; }
            set
            {
                _FirstName = value;
                OnPropertyChanged();
            }
        }

        private void myModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "FirstName")
            {
                MyFirstName = myModel.FirstName;
            }
        }
    }

REFERECE - https://www.codeproject.com/Questions/1055820/How-the-Model-changes-could-be-notified-to-ViewMod

Friday, February 2, 2018

Code Snippet: Read ArcGIS Offline Geodatabase into ArcGIS Runtime in WPF

Be The First To Comment
Here is an quick code snippet for loading ArcGIS runtime database ( offline database) in .NET in ESRI Runtime version 100. The OverlayFeatureLayers() reads the layers from runtime geodatabase and overlayes on runtime environment map in Web Mercator Projection (EPSG: 3857)

 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.IO;  
 using System.Runtime.CompilerServices;  
 using System.Windows.Input;  
 using Esri.ArcGISRuntime.Data;  
 using Esri.ArcGISRuntime.Geometry;  
 using Esri.ArcGISRuntime.Location;  
 using Esri.ArcGISRuntime.Mapping;  
 using Esri.ArcGISRuntime.Security;  
 using Esri.ArcGISRuntime.Symbology;  
 using Esri.ArcGISRuntime.Tasks;  
 using Esri.ArcGISRuntime.UI;  
 using ReadRuntimeGeodatabase.CustomViewModelBase;  
 namespace ReadRuntimeGeodatabase  
 {  
   public class MapViewModel : ViewModelBase  
   {  
     public MapViewModel()  
     {  
       OverlayFeatureLayers();  
     }  
     private Map _map = new Map(SpatialReference.Create(3857));  
     public Map Map  
     {  
       get { return this._map; }  
       set  
       {  
         if (value != this._map)  
         {  
           this._map = value;  
           NotifyPropertyChanged("Map");  
         }  
       }  
     }  
     private async void OverlayFeatureLayers()  
     {  
       Basemap basemap = Basemap.CreateStreets();  
       _map.Basemap = basemap;  
       string gdbsPath = @"C:\RuntimeToFileGeodatabase;  
       DirectoryInfo dirInfo = new DirectoryInfo(gdbsPath);  
       String[] files = dirInfo.GetFiles("*.geodatabase").Select(file => file.FullName).ToArray<string>();  
       foreach (var gdbFile in files)  
       {  
         // open a geodatabase on the local device  
         var gdb = await Esri.ArcGISRuntime.Data.Geodatabase.OpenAsync(gdbFile);  
         // loop thru all tables in the geodatabase  
         foreach (var table in gdb.GeodatabaseFeatureTables.ToList())  
         {  
           table.UseAdvancedSymbology = true;  
           var layer = new FeatureLayer(table);  
           await table.LoadAsync();  
           if (table.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded && table.GeometryType.ToString() != "Unknown")  
           {  
             await layer.LoadAsync();  
             if (layer.Name == "River_line")  
             {  
               // Defaul renderer comes with geodatabase doesn't show up  
               SimpleRenderer customrenderer = new SimpleRenderer();  
               customrenderer.Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Windows.Media.Colors.Black, 2);  
               layer.Renderer = customrenderer;  
               Envelope envelope = layer.FullExtent;  
               _map.InitialViewpoint = new Viewpoint(envelope);  
             }  
             else {  
               if (table.GeometryType.ToString() == "Polyline")  
               {  
                 SimpleRenderer customrenderer = new SimpleRenderer();  
                 customrenderer.Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Windows.Media.Colors.Green, 2);  
                 layer.Renderer = customrenderer;  
               }  
             }             
             System.Diagnostics.Debug.WriteLine(layer.LoadStatus + "---" + layer.Name + "--" + layer.FullExtent + "--" + table.GeometryType + "--" + layer.IsVisibleAtScale(100) + "--" + layer.IsVisible + "--" + layer.MaxScale + "--" + layer.MinScale);  
             if (layer.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)  
             {  
               _map.OperationalLayers.Add(layer);  
             }  
           }  
           else  
           {  
             System.Diagnostics.Debug.WriteLine("No Geom -->" + table.TableName);  
           }  
         }  
       }  
     }  
   }  
 }  

Wednesday, May 31, 2017

Prevent WPF Global Keyboard Hook from stops working after hitting keys a while C# .NET

Be The First To Comment
The article written by Dylan Currier, Low Level Global Keyboard Hook / Sink in C# .NET is one the simple, easily understandable, and and working post on Global Keyboard hook out there in internet. It worked in my WPF application and I added following line in the WPF app to refresh hook after each key press- IDK  if it is write or wrong, more likely to be a wrong practice to hook/unhook every time but it gets the job done. The primary reason to refresh hook is to prevent app hanging (not responding to the key press) after few clicks on the WPF button.

void _listener_OnKeyPressed(object sender, KeyPressedArgs e)
        {
           
          _listener.UnHookKeyboard();
          _listener.HookKeyboard();
        }

Following is the video from Dylan Currier  on Low Level Keyboard Hook in C# / .NET"


Friday, August 19, 2016

Code snippet: Open Folder Browser Dialog in WPF

Be The First To Comment
Install WPFFolderBrowser 1.0.2 from nuget gallery to use the Windows Vista / Windows 7 Folder Browser Dialog from your WPF projects, without any additional dependencies.

Install-Package WPFFolderBrowser
then import WPFFolderBrowser

using WPFFolderBrowser;
private void BrowseFolder()
        {
            WPFFolderBrowserDialog dd = new WPFFolderBrowserDialog();
            var result = dd.ShowDialog();
            if (result.HasValue)
            {
                TxtFvsAccessDbPath = dd.FileName;
            }
        }

Code snippet: WPF UWP ListView SelectionChanged Event Handling in ViewModel

Be The First To Comment
Solution from Dhaval Patel in Sliverlight application works perfectly on my WPF application. I prefer his idea because it is more clear and cleaner than other solutions that  I have came with. The event handling approach explained as -"This is the way where You can Reach the Selection changed events in Your MVVM Application First Of all i tell you that Command Property only work in Button now we have to Explicitly binding that property in our Selection Changed event like List box or combo box in Your XMAL file"
<ListBox Name="MyListBox" ItemsSource="{Binding ListItems}" Height="150" Width="150" Margin="281,32,-31,118">

        <Local:Interaction.Triggers>
            <Local:EventTrigger EventName="SelectionChanged">
                <Local:InvokeCommandAction Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=MyListBox,Path=SelectedItem}"/>
            </Local:EventTrigger>
        </Local:Interaction.Triggers>
    </ListBox>
for this you have to add dll Syatem.Windows.Interactivity now u have to add references in your xaml file namespace like
 xmlns:Local="clr-namespace:System.Windows.Interactivityassembly=System.Windows.Interactivity"

Thursday, August 18, 2016

Code snippet: Data binding between ViewModel and Radio Button in WPF

Be The First To Comment
Following example shows the data binding between radio buttons and ViewModel in WPF.

Parts of View.xaml

<Grid.Resources>
    <Utilities:RadioHelper x:Key="RadioConverter" />
    <Utilities:RadioHelper x:Key="InverseRadioConverter" Inverse="True" />
</Grid.Resources>
<RadioButton Name="radFvsOracle" GroupName="fvsStorage" Content="Oracle" Margin="7,0,0,0" IsChecked="{Binding Path=RadFvsResults, Converter= {StaticResource ResourceKey=RadioConverter}}"></RadioButton>
<RadioButton Name="radFvsAccess" GroupName="fvsStorage" Content="Access" Grid.Column="2" Margin="11,0,0,0" IsChecked="{Binding Path=RadFvsResults, Converter= {StaticResource ResourceKey=InverseRadioConverter}}"></RadioButton>

Parts of RadioHelper.cs

public class RadioHelper:IValueConverter 
    {
        public bool Inverse { get; set; }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                bool boolValue = (bool)value;
                return this.Inverse ? !boolValue : boolValue;
            }
            return Binding.DoNothing;
       }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool boolValue = (bool)value;
            if (!boolValue)
            {
                    return Binding.DoNothing;
            }
            return !this.Inverse;
        }
    }

Friday, August 12, 2016

Multi-item Selection WPF ListBox using Attached Property

Be The First To Comment
The attached property class looks like -
ListBoxHelper.cs
1:  public static class ListBoxHelper  
2:    {  
3:      public static readonly DependencyProperty SelectedItemsProperty =  
4:                          DependencyProperty.RegisterAttached("SelectedItems",   
5:                          typeof(IList),   
6:                          typeof(ListBoxHelper),   
7:                          new PropertyMetadata(default(List<string>),   
8:                          OnSelectedItemsChanged));  
9:        
10:      public static IList GetSelectedItems(DependencyObject d)  
11:      {  
12:        return (IList)d.GetValue(SelectedItemsProperty);  
13:      }  
14:    
15:      public static void SetSelectedItems(DependencyObject d, IList value)  
16:      {  
17:        d.SetValue(SelectedItemsProperty,value);  
18:      }  
19:    
20:      private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)  
21:      {  
22:        var listBox = (ListBox)d;  
23:        ReSetSelectedItems(listBox);  
24:        listBox.SelectionChanged += delegate  
25:        {  
26:          ReSetSelectedItems(listBox);  
27:        };  
28:      }  
29:    
30:      private static void ReSetSelectedItems(ListBox listBox)  
31:      {  
32:        IList selectedItems = GetSelectedItems(listBox);  
33:        selectedItems.Clear();  
34:        if (listBox.SelectedItems != null)  
35:        {  
36:          foreach (var item in listBox.SelectedItems)  
37:            selectedItems.Add(item.ToString());  
38:        }  
39:      }  
40:    }  


Databind between View and ViewModel for PasswordBox WPF

Be The First To Comment
"When you try to databind the password property of a PasswordBox you will recognize that you cannot do data binding on it. The reason for this is, that the password property is not backed by a DependencyProperty.

The reason is databinding passwords is not a good design for security reasons and should be avoided. But sometimes this security is not necessary, then it's only cumbersome that you cannot bind to the password property. In this special cases you can take advantage of the following PasswortBoxHelper.

The PasswordHelper is attached to the password box by calling the PasswordHelper.Attach property. The attached property PasswordHelper.Password provides a bindable copy of the original password property of the PasswordBox control."

Published on -


PasswordHelper.cs
1:  public static class PasswordHelper  
2:  {  
3:    public static readonly DependencyProperty PasswordProperty =  
4:      DependencyProperty.RegisterAttached("Password",  
5:      typeof(string), typeof(PasswordHelper),  
6:      new FrameworkPropertyMetadata(string.Empty, OnPasswordPropertyChanged));  
7:     
8:    public static readonly DependencyProperty AttachProperty =  
9:      DependencyProperty.RegisterAttached("Attach",  
10:      typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false, Attach));  
11:     
12:    private static readonly DependencyProperty IsUpdatingProperty =  
13:      DependencyProperty.RegisterAttached("IsUpdating", typeof(bool),   
14:      typeof(PasswordHelper));  
15:     
16:     
17:    public static void SetAttach(DependencyObject dp, bool value)  
18:    {  
19:      dp.SetValue(AttachProperty, value);  
20:    }  
21:     
22:    public static bool GetAttach(DependencyObject dp)  
23:    {  
24:      return (bool)dp.GetValue(AttachProperty);  
25:    }  
26:     
27:    public static string GetPassword(DependencyObject dp)  
28:    {  
29:      return (string)dp.GetValue(PasswordProperty);  
30:    }  
31:     
 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me