UWP WinRTXamlToolkit: chart-labels with units - charts

For an UWP-app I'm displaying a chart with height data and it currently looks like this:
I'd like to have units for the y-values like 100 m, but I can only manage to get the value itself.
I am able to put a static unit behind that value by "StringFormat" in the "AxisLabelStyle" like this
<Setter Property="StringFormat" Value="{}{0:0 m}" />
but unfortunately I need a dynamic unit (e.g. meters or feet).
Am I missing anything? Ideas?

As we've discussed, this style is set by user. So I just use a ComboBox to select the style for test.
Here is my code:
<Charting:Chart x:Name="AreaChart" Title="Area Chart" Margin="0,0">
<Charting:AreaSeries x:Name="areaseries" IndependentValuePath="Value" DependentValuePath="Number" IsSelectionEnabled="True" />
</Charting:Chart>
<ComboBox x:Name="comboBox" VerticalAlignment="Bottom" SelectionChanged="comboBox_SelectionChanged">
<ComboBoxItem>Meters</ComboBoxItem>
<ComboBoxItem>Feet</ComboBoxItem>
</ComboBox>
code behind is just for testing, I didn't tried to rebuild your chart in your picture:
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
LoadChartContents();
}
private void LoadChartContents()
{
Random rand = new Random();
List<ChartTest> testitem = new List<ChartTest>();
for (int i = 0; i < 30; i++)
{
testitem.Add(new ChartTest() { Value = i, Number = rand.Next(0, 100) });
}
(AreaChart.Series[0] as AreaSeries).ItemsSource = testitem;
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
areaseries.IndependentAxis = new LinearAxis { Orientation = AxisOrientation.X };
var axis = (LinearAxis)areaseries.IndependentAxis;
var item = comboBox.SelectedItem as ComboBoxItem;
if ((string)item.Content == "Meters")
{
var labelstyle = new Style(typeof(AxisLabel));
labelstyle.Setters.Add(new Setter(AxisLabel.StringFormatProperty, "{0:0 m}"));
axis.AxisLabelStyle = labelstyle;
}
else
{
var labelstyle = new Style(typeof(AxisLabel));
labelstyle.Setters.Add(new Setter(AxisLabel.StringFormatProperty, "{0:0 feet}"));
axis.AxisLabelStyle = labelstyle;
}
}
And my is ChartTest class like this:
public class ChartTest
{
public int Value { get; set; }
public int Number { get; set; }
}
The key point here is dynamic adding AxisLabelStyle to AreaSeries in the SelectionChanged event of the ComboBox.

Related

Xamarin.Forms: Is it possible to dynamically add rows to a grid without the ViewModel calling into the VIew?

On a page where I am displaying a receipt to a user, I have a section which lists the subtotal, any taxes, and the total. Since the taxes applicable vary by region and based on the products being sold, the number of rows in this section will vary. For example, here are 3 separate orders, one with GST and PST, one with just GST, and one with neither:
I've accomplished this by putting just the SubTotal in the grid in XAML, and adding the rest in the code-behind in a method I call from the ViewModel. However, I'd really like to avoid doing it this way, so I'm wondering if there is an approach to accomplishing this which doesn't require having the ViewModel know about the View.
A ListView is not suitable here for a number of reasons:
These controls are inside of a ScrollView, and having a ListView inside of a ScrollView causes all sorts of weird problems.
I would like to keep the columns as narrow as their widest element. This is possible with a Grid, but a ListView would take up the entire width of its parent no matter what.
I neither need nor want for my rows to be selectable
So is there a way I can do this without the ViewModel knowing about the View and without resorting to using a ListView?
One way to encapsulate the functionality you require so that the view and the view model are not coupled is by creating a user control.
I created a new user control called TotalsGridControl. Here is the XAML
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ScratchPad.UserControls.TotalsGridControl"
x:Name="TotalsGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
And here is the code behind.
public partial class TotalsGridControl : Grid
{
public TotalsGridControl()
{
InitializeComponent();
}
public static readonly BindableProperty TotalsProperty =
BindableProperty.Create(nameof(Totals), typeof(List<TotalItem>), typeof(TotalsGridControl), null,
BindingMode.OneWay, null, OnTotalsChanged);
private static void OnTotalsChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var control = (TotalsGridControl)bindable;
if (control != null)
{
if (newvalue is List<TotalItem> totals)
{
var rowNumber = -1;
double grandTotal = 0;
foreach (var totalItem in totals)
{
grandTotal += totalItem.Value;
var descLabel = new Label {Text = totalItem.Description};
var valueLabel = new Label { Text = totalItem.Value.ToString("c") };
rowNumber++;
control.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto});
control.Children.Add(descLabel, 0, rowNumber);
control.Children.Add(valueLabel, 1, rowNumber);
}
var grandTotalDescLabel = new Label { Text = "Total" };
var grandTotalValueLabel = new Label { Text = grandTotal.ToString("c") };
rowNumber++;
control.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
control.Children.Add(grandTotalDescLabel, 0, rowNumber);
control.Children.Add(grandTotalValueLabel, 1, rowNumber);
}
}
}
public List<TotalItem> Totals
{
get => (List<TotalItem>)GetValue(TotalsProperty);
set => SetValue(TotalsProperty, value);
}
}
I used a bindable property to allow a list of TotalItem to be bound to the user control.
Here is the data in the view model
public List<TotalItem> Totals { get; set; }
Totals = new List<TotalItem>
{
new TotalItem {Description = "SubTotal", Value = 99.91},
new TotalItem {Description = "GST", Value = 5.0},
new TotalItem {Description = "PST", Value = 4.9}
};
and here is the XAML in the page
<userControls:TotalsGridControl Totals="{Binding Totals}"/>
And the output
Before:
public class ReceiptPageModel : PageModelBase
{
private Receipt _receipt;
public Receipt Receipt
{
get => _receipt;
private set => Set(ref _receipt, value);
}
public override void Init(object initData)
{
Receipt = (Receipt) initData;
((ReceiptPage) CurrentPage).AddTaxes(Receipt);
}
}
After:
public class ReceiptPageModel : PageModelBase
{
private Receipt _receipt;
public Receipt Receipt
{
get => _receipt;
private set => Set(ref _receipt, value);
}
public override void Init(object initData)
{
Receipt = (Receipt) initData;
}
}
public partial class ReceiptPage : FreshBaseContentPage
{
public ReceiptPage()
{
InitializeComponent();
BindingContextChanged += HandlePageModelAdded;
}
private void HandlePageModelAdded(object sender, EventArgs e)
{
var pageModel = (ReceiptPageModel)BindingContext;
if (pageModel.Receipt != null)
{
AddTaxes(pageModel.Receipt);
}
else
{
pageModel.PropertyChanged += (s, args) =>
{
if (args.PropertyName == nameof(pageModel.Receipt))
AddTaxes(pageModel.Receipt);
};
}
}
private void AddTaxes(Receipt receipt)
{
...
}
}

The type 'StackedColumnSeries' does not support direct content [duplicate]

I am trying to use WinRTXamlToolkit.Controls.DataVisualization.UWP
trying to draw any of the stacked charts like this:
But only this comes out:
Please help me, I have to use stacked series but the framework doesn't act as it should be..
Since I don't know how you define the code behind, I just provide the sample code as follows which can create a StackedLineSeries chart successfully.
XAML Code
<Page
x:Class="CStackLineChat.MainPage"
...
xmlns:charting="using:WinRTXamlToolkit.Controls.DataVisualization.Charting"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Padding="50" >
<charting:Chart x:Name="MyChart" Title="Stacked column Chart">
<charting:StackedLineSeries>
<charting:StackedLineSeries.SeriesDefinitions>
<charting:SeriesDefinition
DependentValuePath="Amount"
IndependentValuePath="Name"
IsTapEnabled="True"
Title="Doodad" />
<charting:SeriesDefinition
Title="Stan2"
DependentValuePath="Amount"
IndependentValuePath="Name"/>
</charting:StackedLineSeries.SeriesDefinitions>
</charting:StackedLineSeries>
</charting:Chart>
</Grid>
</Page>
Code behind
public sealed partial class MainPage : Page
{
private Random _random = new Random();
List<NameValueItem> Records = new List<NameValueItem>();
List<NameValueItem> Records2 = new List<NameValueItem>();
public MainPage()
{
this.InitializeComponent();
for (int i = 0; i < 5; i++)
{
Records.Add(new NameValueItem { Name = "Name" + i, Amount = _random.Next(10, 100) });
Records2.Add(new NameValueItem { Name = "Name" + i, Amount = _random.Next(10, 100) });
}
this.RunIfSelected(this.MyChart, () => ((StackedLineSeries)this.MyChart.Series[0]).SeriesDefinitions[0].ItemsSource = Records);
this.RunIfSelected(this.MyChart, () => ((StackedLineSeries)this.MyChart.Series[0]).SeriesDefinitions[1].ItemsSource = Records2);
}
private void RunIfSelected(UIElement element, Action action)
{
action.Invoke();
}
}
public class NameValueItem
{
public string Name { get; set; }
public int Amount { get; set; }
}
And the result
Additionally, by testing on my side, it seems like DependentValuePath and IndependentValuePath properties can not directly binding in your scenario. The best way to use this package is to follow the official sample. Here is the chart sample.

ZK Reordering With Listbox Without Drag And Drop Event

As i am trying This example well define by Nabil Abdel-Hafeez
It is working fine with some small issue which i already mentioned in tracker as issue. But i will want to Open a DualBox modal window in which one listbox contain all header name and other listbox will contain which header we will want to show for a listbox(I did this with getitemrendered ).I will want to use same ZUL Code without getitemrendered method.But user can hide the header which he/she do not want to see for a listbox. Anyone did this type of things?
Here
The green image with + Sign showing same thing which i will want to implement.
As I was trying the Nabil Abdel-Hafeez but my issue is that i will provide duallistbox where user can select which header he/she will want to see in listbox, user can select header by clicking on button ,user can add one header or all header from duallistbox and when user click on the Reorder button of duallistbox then it will reorder .In Nabil demo he is doing something like this..
for (Listitem item : lHead.getListbox().getItems()) {
item.insertBefore(item.getChildren().get(from), item.getChildren().get(to));
}
But if user selecting multiple how we will track which will come first which second and so on..
You can try combine MVVM with forEach so you can construct String array to display, this works since 6.0.2
e.g.,
zul
<zk>
<div apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('test.TestVM')">
<listbox model="#load(vm.model)">
<listhead>
<listheader forEach="${vm.headers}" label="${each}" />
</listhead>
<template name="model" var="cells">
<listitem>
<listcell forEach="${cells}" label="${each}" />
</listitem>
</template>
</listbox>
<button label="original seq" onClick="#command('originalSeq')" />
<button label="reverse" onClick="#command('reverse')" />
</div>
</zk>
VM
package test;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import java.util.*;
public class TestVM {
private int[] _original = {1, 2, 3};
private int[] _reverse = {3, 2, 1};
private int[] _seq = _original;
private List _rawData;
public String[] getHeaders () {
String[] headers = new String[_seq.length];
for (int i = 0; i < _seq.length; i++) {
int idx = _seq[i];
headers[i] = (idx == 1? "First Name" :
idx == 2? "Last Name" :
idx == 3? "Age" : "");
}
return headers;
}
public ListModel getModel () {
if (_rawData == null) {
getRawData();
}
List modelData = new ArrayList();
for (int i = 0; i < _rawData.size(); i++) {
Person data = (Person)_rawData.get(i);
String[] cells = new String[_seq.length];
for (int j = 0; j < _seq.length; j++) {
cells[j] = data.getValue(_seq[j]);
}
modelData.add(cells);
}
return new ListModelList(modelData);
}
public void getRawData () {
_rawData = new ArrayList();
_rawData.add(new Person("First Name 01", "Last Name 01", 21));
_rawData.add(new Person("First Name 02", "Last Name 02", 22));
_rawData.add(new Person("First Name 03", "Last Name 03", 23));
}
#Command
#NotifyChange("model")
public void originalSeq () {
_seq = _original;
}
#Command
#NotifyChange("model")
public void reverse () {
_seq = _reverse;
}
class Person {
private String _firstName;
private String _lastName;
private int _age;
public Person (String firstName, String lastName, int age) {
_firstName = firstName;
_lastName = lastName;
_age = age;
}
public String getFirstName () {
return _firstName;
}
public String getLastName () {
return _lastName;
}
public int getAge () {
return _age;
}
public String getValue (int i) {
return i == 1? getFirstName() :
i == 2? getLastName() :
i == 3? getAge() + "" : "";
}
}
}
Regarding forEach, please refer to ZK Iterative Evaluation
Edit
Fully binded sample at ZK fiddle
Listbox Reorder Cells

How to get actual value and validate of CustomTextbox Text in ViewModel

I have created custom component for displaying text with either Simple or Password mode, intention to develop this control is the Silverlight does not support custom TextMode (like Password or Text).
This is my requirement
In addition to the access rights it will be possible for organizations to specify restricted access to certain fields in the database. The access restriction to these fields will be Update and Redacted, thus meaning if a specific field has true against Update then a user will be able to update the field as well as viewing it, and if the field has true against Redacted then the user will only be able to see a redacted value in the filed (possibly asterisks - * * * * *). It will be possible to set a field to being Update-able and Redacted, thus meaning a user will see the redacted view but still be able to go and update the field with a new value. Such a requirement is mostly used when holding sensitive information against a contact or information which could be used to discriminate against the contact.
I have created custom control for this requirement and it is working perfectly. i am able to set TextMode dynamically but i couldn't able to get the original value in my ViewModel. (I am able to get original value in View but can't in ViewModel)
If i am access the original value in View using following then it is work.
string s = UserName.Text;
but not getting this value in ViewModel it is giving me like **.
Following is the complete code for PasswordTextBox control.
namespace QSys.Library.Controls
{
public partial class PasswordTextBox : TextBox
{
#region Variables
private string text = string.Empty;
private string passwordChar = "*";
private int selectionLength = 0;
#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 (Mode)GetValue(TextModeProperty); }
set { SetValue(TextModeProperty, value); }
}
public static readonly DependencyProperty TextModeProperty = DependencyProperty.Register("TextMode", typeof(Mode), typeof(PasswordTextBox), new PropertyMetadata(default(Mode)));
#endregion
#region Constructors
public PasswordTextBox()
{
this.Loaded += new RoutedEventHandler(PasswordTextBox_Loaded);
}
#endregion
#region Event Handlers
void PasswordTextBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
if (this.TextMode == Mode.Password)
{
text = base.Text;
this.TextChanged += new TextChangedEventHandler(PasswordTextBox_TextChanged);
this.KeyDown += new KeyEventHandler(PasswordTextBox_KeyDown);
this.SelectionChanged += new RoutedEventHandler(PasswordTextBox_SelectionChanged);
DisplayMaskedCharacters();
}
this.Loaded -= PasswordTextBox_Loaded;
}
void PasswordTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
selectionLength = this.SelectionLength;
}
public void PasswordTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
if (base.Text.Length >= text.Length)
text += base.Text.Substring(text.Length);
else
{
int cursorPosition = this.SelectionStart;
selectionLength = (selectionLength > 1) ? selectionLength : 1;
text = text.Remove(cursorPosition, selectionLength);
}
DisplayMaskedCharacters();
selectionLength = 0;
}
public void PasswordTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int cursorPosition = this.SelectionStart;
// Handle Delete and Backspace Keys Appropriately
if (e.Key == System.Windows.Input.Key.Back && cursorPosition > 0)
{
DeleteAt(cursorPosition);
}
else if (e.Key == System.Windows.Input.Key.Delete)
{
DeleteAt(cursorPosition);
}
else
{
if (selectionLength > 0) text = text.Remove(cursorPosition, selectionLength);
base.Text = text;
this.Select((cursorPosition > text.Length ? text.Length : cursorPosition), 0);
DisplayMaskedCharacters();
}
selectionLength = 0;
}
#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);
}
private void DeleteAt(int position)
{
if (text.Length > position)
{
text = text.Remove(position, 1);
base.Text = base.Text.Remove(position, 1);
}
}
#endregion
}
}
LoginView.xaml
<control:PasswordTextBox x:Name="UserName" TabIndex="1" Grid.Row="1" TextMode="Password" Text="{Binding Path=LoginModelValue.UserName, Mode=TwoWay,ValidatesOnNotifyDataErrors=True, ValidatesOnExceptions=True, ValidatesOnDataErrors=True, NotifyOnValidationError=True}" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Width="200" Height="25" Validatevalue:UpdateSourceTriggerHelper.UpdateSourceTrigger="True"/>
LoginViewModel.cs
public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime
{
public LoginModel LoginModelValue
{
get { return _LoginModelValue; }
set
{
_LoginModelValue = value;
OnPropertyChanged("LoginModelValue");
}
}
}
LoginModel.cs
namespace QSys.Model
{
public class LoginModel : INotifyPropertyChanged
{
#region Variables
private string _userName;
private string _password;
#endregion
#region Constructor
public LoginModel()
{
}
#endregion
#region Properties
[CustomValidation(typeof(PasswordTextBox), "IsValidUserName")]
[Required(ErrorMessage = "User Name is required")]
[Display(Name = "UserName")]
[StringLength(50)]
//[RegularExpression(#"^[a-zA-Z\\0-9\\.\\,\\'\s]+$", ErrorMessage = "Please enter right format.")]
public string UserName
{
get { return _userName; }
set
{
_userName = value;
OnPropertyChanged("UserName");
ValidateProperty("UserName", value);
}
}
[Required(ErrorMessage = "Password is required")]
[Display(Name = "Password")]
[StringLength(10)]
public string Password
{
get { return _password; }
set
{
_password = value;
OnPropertyChanged("Password");
ValidateProperty("Password", value);
}
}
#endregion
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
#region Private Methods
public bool IsValidObject()
{
ICollection<ValidationResult> results = new Collection<ValidationResult>();
return Validator.TryValidateObject(this, new ValidationContext(this, null, null), results, true) && results.Count == 0;
}
public void ValidateProperty(string propertyName, object value)
{
Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = propertyName });
}
#endregion
}
}
**I am looking for solution since two days without any luck.
Please help me if you have any solution, your comments or suggestion would be highly appreciated.**
Thanks
Imdadhusen
Wouldn't it be easier to build your own UserControl around the regular TextBox and PasswordBox and just switching their visibility when your dependency property TextMode changes? You could then have a single VM for the UserControl with property Value and bind in TwoWay mode both the TextProperty of the TextBox and the Password property of the PasswordBox to it.
I have resolved using following code.
I am missing Mode=TwoWay in LoginView.xaml:
<control:RestrictedBox Type="Text" Value="{Binding Path=UserName,Mode=TwoWay}">
Thanks,
Imdadhusen

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