Binding Properties within a Class which is a Property within a ViewModel - mvvm

I have a MainPageViewModel coded as below which has Properties which are bound through a View.
For example:
private string _status;
public string Status
{
get { return _status; }
set
{
_status = value;
OnPropertyChanged(nameof(Status));
}
}
Full MainPageViewModel.cs at:
https://github.com/mainroads/SpecifiedRecordsExporter/blob/mvvm/SpecifiedRecordsExporter/MVVM/ViewModels/MainPageViewModel.cs
For example, they are bound as below in the View:
<Label x:Name="lblStatus" Text="{Binding Status}"></Label>
Full XAML at:
https://github.com/mainroads/SpecifiedRecordsExporter/blob/mvvm/SpecifiedRecordsExporter/MVVM/Views/MainPage.xaml
I was hoping to move these Properties to an AppDataModel class as below:
https://github.com/mainroads/SpecifiedRecordsExporter/blob/mvvm/SpecifiedRecordsExporter/MVVM/Models/AppDataModel.cs
I would then access all the properties through an AppData object:
private AppDataModel _appData = new AppDataModel();
public AppDataModel AppData
{
get { return _appData; }
set
{
_appData = value;
OnPropertyChanged(nameof(AppData));
}
}
That way, my plan was to bound the same Properties as below:
<Label x:Name="lblStatus" Text="{Binding AppData.Status}"></Label>
However, once I do this change, the Properties are not bound.
Is this a limitation in Net or am I missing something?
Thanks,
Michael
P.S:
I have tried to create the AppData Property the same way, but to no avail:
// TODO: Try AppData
/*
private AppDataModel _appData = new AppDataModel();
public AppDataModel AppData
{
get { return _appData; }
set
{
_appData = value;
OnPropertyChanged(nameof(AppData));
}
}
*/
AppDataModel.cs inherits the ObservableModel.cs:
https://github.com/mainroads/SpecifiedRecordsExporter/blob/mvvm/SpecifiedRecordsExporter/MVVM/Models/ObservableModel.cs

Related

Xamarin Passing and checking data to other view using MVVM

So far I can pass the value to the other view but the problem is I don't know how to do this using MVVM. I tried the documentations and tutorial still no luck. How can I achieve this?
The flow of my project:
- The user will login, when the user provides the correct it will return a JSON array that contains the ContactID of the user.
- This ContactID now be pass to the other view. It will be used to synchronize the server to the local database and vice versa
My Questions are:
1. How can I pass the data to other view with MVVM?
2. How can I check if the data is passed correctly?
The Output of the HTTPWebRequest:
[{"ContactID":"1"}]
My Code:
LoginPageViewModel.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Input;
using TBSMobileApplication.Data;
using TBSMobileApplication.View;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace TBSMobileApplication.ViewModel
{
public class LoginPageViewModel : INotifyPropertyChanged
{
void OnPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public string username;
public string password;
public string Username
{
get { return username; }
set
{
username = value;
OnPropertyChanged(nameof(Username));
}
}
public string Password
{
get { return password; }
set
{
password = value;
OnPropertyChanged(nameof(Password));
}
}
public class LoggedInUser
{
public int ContactID { get; set; }
}
public ICommand LoginCommand { get; set; }
public LoginPageViewModel()
{
LoginCommand = new Command(OnLogin);
}
public void OnLogin()
{
if (string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password))
{
MessagingCenter.Send(this, "Login Alert", Username);
}
else
{
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
var link = "http://192.168.1.25:7777/TBS/test.php?User=" + Username + "&Password=" + Password;
var request = HttpWebRequest.Create(string.Format(#link));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
else
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (content.Equals("[]") || string.IsNullOrWhiteSpace(content) || string.IsNullOrEmpty(content))
{
MessagingCenter.Send(this, "Http", Username);
}
else
{
var result = JsonConvert.DeserializeObject<List<LoggedInUser>>(content);
var contactId = result[0].ContactID;
Application.Current.MainPage.Navigation.PushAsync(new DatabaseSyncPage(contactId), true);
}
}
}
}
}
else
{
MessagingCenter.Send(this, "Not Connected", Username);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
DatabaseSyncPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace TBSMobileApplication.View
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DatabaseSyncPage : ContentPage
{
public DatabaseSyncPage (int contanctId)
{
InitializeComponent ();
}
}
}
If you are new to MVVM i would highly recommend using an MVVM helper framework such as Prism, MVVMCross or MVVMLight (there are even more).
I myself use Prism, I believe all of the frameworks are functionally very similar and it comes down more to preference here. I will show you how I pass data between views in my Prism based applications. Before we get started it would be worth to download the prism visual studio extensions and use the template pack to generate a prism project. I use the DryIoc container.
Imagine the scenario where we have ViewA (with ViewAViewModel) and ViewB (with ViewBViewModel). In View A we have an Entry and a Button, when the button is pressed the text from the entry in ViewA is passed to ViewB where it is displayed in a label.
You would first setup your prism project, creating a XAML fronted view for View A & B and then creating 2 class files and creating the relevant View Models (I'll show you how).
Firstly creating the following files:
ViewA (Xaml content page)
ViewB (Xaml content page)
ViewAViewModel (empty class)
ViewBViewModel (empty class)
In your app.cs register the views and view models:
//You must register these views with prism otherwise your app will crash!
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<ViewA, ViewAViewModel>();
containerRegistry.RegisterForNavigation<ViewB, ViewBViewModel>();
}
Now format your view models by adding the following:
public class ViewAViewModel : ViewModelBase
{
INavigationService _navigationService;
public ViewAViewModel(INavigationService navigationService) : base(navigationService)
{
Title = "ViewA";
_navigationService = navigationService;
}
}
Repeat the above step for ViewBViewModel also (changing the relevant names).
Now in the views xaml lets add some stuff! Add the following to ViewA.xaml (inside <ContentPage.Content></ContentPage.Content>:
<StackLayout>
<Entry Placeholder="Type Here..." Text="{Binding ViewAText}"/>
<Button Text="Navigate" Command="{Binding OnNavigateCommand}"/>
</StackLayout>
and in ViewB.xaml:
`<Label Text="{Binding TextFromViewA}"/>`
Now I've already added the binding for you, so lets make the properties!
In View Model A add:
private string _viewAText;
public string ViewAText
{
get { return _viewAText; }
set { SetProperty(ref _viewAText, value); }
}
public DelegateCommand OnNavigateCommand { get; set; }
private void OnNavigate()
{
//Do Something
}
Now we have a bindable property and a command for our button press, add the following to the constructor:
public ViewAViewModel(INavigationService navigationService) : base(navigationService)
{
Title = "ViewA";
_navigationService = navigationService;
_viewAText = string.Empty;
OnNavigateCommand = new DelegateCommand(OnNavigate);
}
Now View A can bind text from the entry control and has an event handler for the command!
Lets hop into View B and wire that up!
Add the property:
private string _textFromViewA;
public string TextFromViewA
{
get { return _textFromViewA; }
set { SetProperty(ref _textFromViewA, value); }
}
and in the constructor:
public ViewBViewModel(INavigationService navigationService) : base(navigationService)
{
Title = "ViewB";
TextFromViewA = string.Empty;
}
Now the label we added in ViewB is hooked up to the view model. Lets now pass the text from the entry in A to B!
Back in View A add the following to the OnNavigate method:
private void OnNavigate()
{
NavigationParameters navParams = new NavigationParameters();
navParams.Add("PassedValue", _viewAText);
_navigationService.NavigateAsync("ViewB", navParams);
}
The navigation service is incredibly powerful and allows you to pass a dictionary between views (NavigationParameters). In this code we have created some NavigationParameter, added the value of the text in our entry to them and then asked the navigationService (which handles all navigation from viewmodels in Prism) to navigate to ViewB, passing the parameters to it.
In View B we can listen for these parameters using some built in methods provided by Prism. If you type override in ViewBViewModel you will see the methods:
OnNavigatingTo
OnNavigatedTo
OnNavigatedFrom
In this case we want to use OnNavigatingTo (which is fired during the transition between the views). Pull that method in and the following:
public override void OnNavigatingTo(NavigationParameters parameters)
{
base.OnNavigatingTo(parameters);
if (parameters.ContainsKey("PassedValue"))
{
_textFromViewA = (string)parameters["PassedValue"];
RaisePropertyChanged("TextFromViewA");
}
}
Here we check if the parameters contain the value we added (by searching for the dictionary key) and then retrieve the value (casting it to a string since the dictionary is ). We then set the property the label is bound to = to the passed value and then use a prism method, RaisePropertyChanged() to raise a property changed event so that the label's binded value updates!
Below is a gif of the results!
This might be alot to take in. I would advise you start using an MVVM framework asap, they are really easy to use and I would consider them essential to making testable, decoupled MVVM xamarin apps!
For more on how prism works, I'd suggest to go read the docs and watch Brian Lagunas' appearance on the Xamarin Show!
Good Luck!
i had implemented the same and hope this helps you.
i have create a loginViewModel
public class LoginVerificationVM : BaseViewModel // INotifyPropertyChanged
{
private INavigation _navigation;
private string usermobileno;
public string UserMobileNo
{ get { return usermobileno; }set { usermobileno = value;
OnPropertyChanged("UserMobileNo"); }
}
public LoginVerificationVM(INavigation navigation, string mobileno)
{
UserMobileNo = mobileno;
_navigation = navigation;
}
public Command Login
{
get
{
return new Command(async () =>
{
bool status = await WebApi.CheckNetWorkStatus();
if (status == false)
{
MessageClass.messagesWindow("Check Ur Connectivity");
this.Isvisible = false;
return;
}
Isvisible = true;
UserAuth ud = new UserAuth();
ud.username = UserMobileNo; // UserMobileNo;
ud.password = Password; // Password
ud.grant_type = "password"; //GrantType
Isvisible = true;
// IsBusy = false;
await Task.Delay(100);
var json = Task.Run(() => WebApi.GetUserAuth(ud)).Result;
// IsBusy = false;
if (json.ErrorMessage == "true")
{
Application.Current.MainPage = new MasterPages.MasterPage(json.access_token); //or use _navigation.PushAsync(new ForgotPasswordOTP(UserMobileNo));
}
else
{
MessageClass.messagesWindow(json.ErrorMessage);
}
Isvisible = false;
});
}
}
}
Xaml Code
<Entry x:Name="PasswordEntry" Grid.Row="2" IsPassword="True" Placeholder="******" HorizontalTextAlignment="Center" FontAttributes="Bold" TextColor="Black" WidthRequest="150" HeightRequest="35" FontSize="13" Text="{Binding Password, Mode=TwoWay}" >
<Button x:Name="Login" Grid.Row="3" HorizontalOptions="Center" BorderRadius="8" Text="Login" WidthRequest="100" BackgroundColor="#f7941d" TextColor="White" Command="{Binding Login}" IsEnabled="{Binding Active,Mode=TwoWay}">
here is implementation to get data on navigated page view model
public ForgotPasswordOTP(string Ph)
{
InitializeComponent();
BindingContext = new ForgotPasswordOTPViewModel(this.Navigation,Ph);
}
and the last thing you need to do is bind your view with your viewmodel
** BindingContext = new LoginVerificationVM(this.Navigation);**
And the answer for the last question is you need to deserialize json in c#
which can be done in following way
var userData = JsonConvert.DeserializeObject<YourObject>(result);

Best practice for nesting ContentViews into ContentPage as Xamarin architecture

I am have an app that basically loads a bunch of ContentViews into the home ContentPage. I THINK there is a problem here because all of the viewmodels would essentially need to been initialized every time we load the home page. I am wondering if it is worth my time to ditch the below code and convert the views from ContentView's to ContentPage's and just do Navigation.PushAsync(new View1()); instead. Sorry I know this is alot of example code but I would really like to get a clear picture of best practice.
My Home.xaml
<Grid x:Name="ContentBody" VerticalOptions="FillAndExpand">
<local:View1 Grid.Row="0" x:Name="View1" IsVisible="{Binding View1IsVisible}" BindingContext="{Binding View1ViewModel}" />
<local:View2 Grid.Row="0" x:Name="View2" IsVisible="{Binding View2IsVisible}" BindingContext="{Binding View2ViewModel}" />
<local:View3 Grid.Row="0" x:Name="View3" IsVisible="{Binding View3IsVisible}" BindingContext="{Binding View3ViewModel}" />
<local:View4 Grid.Row="0" x:Name="View4" IsVisible="{Binding View4IsVisible}" BindingContext="{Binding View4ViewModel}" />
<local:View5 Grid.Row="0" x:Name="View5" IsVisible="{Binding View5IsVisible}" BindingContext="{Binding View5ViewModel}" />
<local:View6 Grid.Row="0" x:Name="View6" IsVisible="{Binding View6IsVisible}" BindingContext="{Binding View6ViewModel}" />
<local:DrawerView Grid.Row="0" x:Name="DrawerView" IsVisible="{Binding DrawerViewIsVisible}" />
</Grid>
Then In my HomeViewModel...
private readonly View1ViewModel _view1ViewModel = new View1ViewModel();
public View1ViewModel View1ViewModel { get { return _view1ViewModel; } }
private readonly View2ViewModel _view2ViewModel = new View2ViewModel();
public View2ViewModel View2ViewModel { get { return _view2ViewModel; } }
private readonly View3ViewModel _view3ViewModel = new View3ViewModel();
public View3ViewModel View3ViewModel { get { return _view3ViewModel; } }
private readonly View4ViewModel _view4ViewModel = new View4ViewModel();
public View4ViewModel View4ViewModel { get { return _view4ViewModel; } }
private readonly View5ViewModel _view5ViewModel = new View5ViewModel();
public View5ViewModel View5ViewModel { get { return _view5ViewModel; } }
private readonly View6ViewModel _view6ViewModel = new View6ViewModel();
public View6ViewModel View6ViewModel { get { return _view6ViewModel; } }
///////////////////Some Visibility Properties...//////////////////////
///////////////////Some Visibility Properties...//////////////////////
private bool _view1IsVisible;
public bool View1IsVisible
{
get { return _view1IsVisible; }
set { _view1IsVisible = value; OnPropertyChanged("View1IsVisible"); }
}
private bool _view2IsVisible;
public bool View2IsVisible
{
get { return _view2IsVisible; }
set { _view2IsVisible = value; OnPropertyChanged("View2IsVisible"); }
}
private bool _view3IsVisible;
public bool View3IsVisible
{
get { return _view3IsVisible; }
set { _view3IsVisible = value; OnPropertyChanged("View3IsVisible"); }
}
private bool _view4IsVisible;
public bool View4IsVisible
{
get { return _view4IsVisible; }
set { _view4IsVisible = value; OnPropertyChanged("View4IsVisible"); }
}
private bool _view5IsVisible;
public bool View5IsVisible
{
get { return _view5IsVisible; }
set { _view5IsVisible = value; OnPropertyChanged("View5IsVisible"); }
}
private bool _view6IsVisible;
public bool View6IsVisible
{
get { return _view6IsVisible; }
set { _view6IsVisible = value; OnPropertyChanged("View6IsVisible"); }
}
/////And then this is more or less a method to show the view/////////////
private void ShowView(ViewChangedEventArgs e)
{
HideAllViews();
switch(e.SelectedView){
case ViewType.View1:
View1IsVisible = true
break;
case ViewType.View2:
View2IsVisible = true
break;
case ViewType.View3:
View3IsVisible = true
break;
case ViewType.View4:
View4IsVisible = true
break;
case ViewType.View5:
View5IsVisible = true
break;
case ViewType.View6:
View6IsVisible = true
break;
}
}
Can someone tell me if this approach is fine? as using this approach everytime I add a new page I will need to add a view to the Homepage view and the viewModel & IsVisible properties to the Homepage ViewModel..
I would greatly appreciate any guidance on this. I think a better approach would be to just seperate the ContentViews from the HomePage and when I Navigate to one of these views I would just PushAsync. I have seen supporting documentation online where some people are taking the above approach, I am just trying to ask the experts what they think when they see this code.
After speaking w/ a member of the Xamarin team I've been told to remove all the views from this homeview page, bind the perspective view models in their own code behinds, and from there I can navigation using Navigation.PushAsync(new View1());
Tutorial:
https://github.com/XamarinUniversity/XAM290
Documentaiton:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/enterprise-application-patterns/

Caliburn Micro MVVM getting comboBox to display a ViewModel screen

I have a combobox displaying the lists within it perfectly in the ViewModel but I'm looking to have it so that when a selected item from the list is chosen it fires the ViewModel screen and I only want one from the list to do this?
So here is what I have in the ChooseView:
<ComboBox x:Name="CatalogName1" SelectedItem="{Binding SelectedCatalog1}" Style="{DynamicResource appComboBox}" Grid.Row="1" Grid.Column="1" >
</ComboBox>
and in the ChooseViewModel:
public List<string> CatalogName1
{
get
{
return new List<string> { "New", "Replace", "Extended", "Nothing", "ShowScreen" };
}
}
private string selectedCatalog1;
public string SelectedCatalog1
{
get
{
return this.selectedCatalog1;
}
set
{
this.selectedCatalog1 = value;
this.NotifyOfPropertyChange(() => this.SelectedCatalog1);
}
}
the "ShowScreen" in the combo list should display the ShowScreenViewModel but I have tried with the getter setter and it's not making sense to me
Okay, this is the way I would fix the problem...
private string selectedCatalog1;
public string SelectedCatalog1
{
get
{
return selectedCatalog1;
}
set
{
selectedCatalog1 = value;
ValidateValue(value);
NotifyOfPropertyChange(() => SelectedCatalog1);
}
}
private void ValidateValue(string s)
{
if (s == "ShowScreen")
{
ActivateItem(new ShowScreenViewModel());
}
}

RaiseCanExecuteChanged more convenience

I'd like to RaiseCanExecuteChanged when CanExecute condition got changed.
E.g.:
public class ViewModel
{
public viewModel()
{
Command = new RelayCommand(action,condition);
}
private bool condition()
{
return this.Condition1&&this.Condition2&&this.Condition3;
}
public bool Condition1
{
get{...}
set{.... **command.RaiseCanExecuteChanged();}**
}
public bool Condition2
{
get{...}
set{.... command.**RaiseCanExecuteChanged();}**
}
public bool Condition3
{
get{...}
set{.... **command.RaiseCanExecuteChanged();}**
}
}
That works fine.
But I don't like to write so many RaiseCanExecuteChanged, I want to set these changes automatically.
E.g
In RelayCommand, create a new method named RaiseChanged
public void RaiseChanged(XXXXXX XXX, params string[] propertyNames)
{
// for each property in propertyNames,
// RaiseCanExecuteChanged();
}
I put ViewModel vm as the parameters, and use vm.PropertyChanged+=(s,e)=>{}
But I don't think it's a good way to do this.
Does anyone have other ideas?
I develop my solution where I can do like that:
C# View Model:
public bool CanExecuteMethod(object sender)
{
}
public void ButtonExecuteMethod(object sender)
{
}
public event Action EventNotifyCanExecuteChanged;
private Action _DelegateNotifyCanExecuteChanged;
public Action DelegateNotifyCanExecuteChanged
{
get { return _DelegateNotifyCanExecuteChanged; }
set { _DelegateNotifyCanExecuteChanged = value; }
}
public void CanExecuteFlag
{
if (EventNotifyCanExecuteChanged != null) { EventNotifyCanExecuteChanged(); }
if (_DelegateNotifyCanExecuteChanged != null) { _DelegateNotifyCanExecuteChanged();}
}
XAML:
< Button Content="Button Cmd-ExCeCh" HorizontalAlignment="Left" Margin="27,231,0,0"
VerticalAlignment="Top" Width="120"
Command="{mark:BindCommandResource MainWindowViewModel,
ExecuteMethodName=ButtonExecuteMethod,
CanExecuteMethodName=CanExecuteMethod,
EventToInvokeCanExecuteChanged=EventNotifyCanExecuteChanged,
PropertyActionCanExecuteChanged=DelegateNotifyCanExecuteChanged}" />
I put/share this solution in my open source project MVVM-WPF XAML Mark-up Binding Extensions - http://wpfmvvmbindingext.codeplex.com

Error in Binding Custom Textbox Property

I have created custom Textbox in Silverlight 4, MVVM and PRISM 4. The custom text box has dynamic behavior link it dynamically set TextMode to either Password or Text.
This is working perfect. ( if i am bind TextMode static)
<control:PasswordTextBox x:Name="customTextBox2" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="Password"/>
This is giving me an error (if i am binding with dynamic)
<control:PasswordTextBox x:Name="customTextBox1" Width="100" Height="30" Grid.Row="4" Grid.Column="1" Text="{Binding Email}" TextMode="{Binding WritingMode}"/>
following is my ViewModel code
[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class UserRightsViewModel : NotificationObject, IRegionMemberLifetime
{
private Mode _writingMode = Mode.Text;
public Mode WritingMode
{
get { return _writingMode; }
set
{
_writingMode = value; RaisePropertyChanged("WritingMode");
}
}
[ImportingConstructor]
public UserRightsViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
{
UserSecurity security = new UserSecurity();
FormSecurity formSecurity = security.GetSecurityList("Admin");
formSecurity.WritingMode = Mode.Password;
}
}
following is the enum
namespace QSys.Library.Enums
{
public enum Mode
{
Text,
Password
}
}
following code for Custom PasswordTextBox
namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string _Text = string.Empty;
private string _PasswordChar = "*";
private Mode _TextMode = Mode.Text;
#endregion
#region Properties
/// <summary>
/// The text associated with the control.
/// </summary>
public new string Text
{
get { return _Text; }
set
{
_Text = value;
DisplayMaskedCharacters();
}
}
/// <summary>
/// Indicates the character to display for password input.
/// </summary>
public string PasswordChar
{
get { return _PasswordChar; }
set { _PasswordChar = value; }
}
/// <summary>
/// Indicates the input text mode to display for either text or password.
/// </summary>
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
#endregion
#region Constructors
public PasswordTextBox()
{
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new System.Windows.Input.KeyEventHandler(PasswordTextBox_KeyDown);
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion
#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
//this.TextChanged += ImmediateTextBox_TextChanged;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= _Text.Length) _Text += base.Text.Substring(_Text.Length);
DisplayMaskedCharacters();
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
int selectionLength = this.SelectionLength;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back || e.Key == System.Windows.Input.Key.Delete)
{
if (cursorPosition < _Text.Length)
_Text = _Text.Remove(cursorPosition, (selectionLength > 0 ? selectionLength : 1));
}
base.Text = _Text;
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
#endregion
#region Private Methods
private void DisplayMaskedCharacters()
{
int cursorPosition = this.SelectionStart;
// This changes the Text property of the base TextBox class to display all Asterisks in the control
base.Text = new string(_PasswordChar.ToCharArray()[0], _Text.Length);
this.Select((cursorPosition > _Text.Length ? _Text.Length : cursorPosition), 0);
}
#endregion
#region Public Methods
#endregion
}
}
I am getting following error if i am binding with dynamically.
Set property 'QSys.Library.Controls.PasswordTextBox.TextMode' threw an exception. [Line: 40 Position: 144]
Your answer would be appreciated.
Thanks in advance.
Imdadhusen
Try to change in your PasswordTextBox class
public Mode TextMode
{
get { return _TextMode; }
set { _TextMode = value; }
}
to
public static readonly DependencyProperty TextModeProperty =
DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
public Mode TextMode
{
get { return (Mode) GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
You can read more here:
Dependency Properties Overview
DependencyProperty Class
The main paragraph from the second link is:
A DependencyProperty supports the following capabilities in Windows
Presentation Foundation (WPF):
....
The property can be set through data binding. For more information about data binding dependency properties, see How to: Bind the
Properties of Two Controls.
I provide links for WPF, but basically for Silverlight it's the same