Binding of Label Text from mongodb retrieved value - mongodb

I'm having issues binding my label text to the userValue calculated from my mongoDB collection.
I've tried this multiple ways now and would like to simply have this work in the Xamarin's code behind. Please would you provide better guidance than is already out there as current posts on this have not worked...
My XAML:
<Label x:Name="YourLableName"
Text="{Binding UserValue, StringFormat='{0:0}'}"
/>
My CS:
public HomePage()
{
InitializeComponent();
BindingContext = this;
UserData();
}
public async void UserData()
{
var userId = HomePage.userIdentity;
var usersValues = await MongoService.GetUserModel(userId);
foreach (var test in usersValues)
{
userValue = test.usersValueX.ToString();
}
UserValue = userValue;
}
private string _UserValue;
public string UserValue
{
get { return _UserValue; }
set
{
_UserValue = value;
OnPropertyChanged("UserValue");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String info)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(info));
}
}
Thank you :)
P.s. I have breakstopped this at UserValue and the value is retrieved in the UserData method however it still does not bind to my label text...

It didn't work because my content page was wrapped in a control template :/ .

Related

How to implement Activity/Wait Indicator in dotnet Maui?

I needed to implement a wait indicator for a page in my Maui app.
Searching gave me this, but no step by step instructions.
So how do I do this?
Overview:
The control to display the animation is called ActivityIndicator.
ActivityIndicator is a visual element, should be part of your page.
So, add an ActivityIndicator to your xaml.
The state of the indicator is part of logic - should live in your view model.
So, add a bindable property to your view model, and bind ActivityIndicator.IsRunning to this property.
Sample (I haven't tested, just for illustration)
Page (xaml):
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:customcontrols="clr-namespace:Waiter.Maui.CustomControls"
x:Class="..." >
<ContentPage.Content>
<ActivityIndicator IsRunning="{Binding IsBusy}" />
<Button Text="Go" Command="{Binding GoCommand}" />
</ContentPage.Content>
</ContentPage>
ViewModel:
namespace MyNamespace
{
public class MyViewModel : BaseViewModel
{
public MyViewModel()
{
GoCommand = new Command(execute: OnGo, canExecute: true);
}
public Command GoCommand { get; }
private void OnGo()
{
MainThread.InvokeOnMainThreadAsync(async () =>
{
IsBusy = true;
Thread.Sleep(5000);
IsBusy = false;
return result;
});
}
}
}
BaseViewModel class (so that it can be re-used, from existing community content):
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Waiter.Maui.Pages
{
public class BaseViewModel : INotifyPropertyChanged
{
bool isBusy = false;
public bool IsBusy
{
get { return isBusy; }
set { SetProperty(ref isBusy, value); }
}
string title = string.Empty;
public string Title
{
get { return title; }
set { SetProperty(ref title, value); }
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
}
I want to point out few things.
First of all, this "IsBusy" that I see getting recommended all around, is working strategy. I can only recommend using CommunityToolkit.MVVM, and letting it do your job, and handle all notification code instead of you.
However, using such boolean variable, is no different than using Lock, Mutex, Semaphore, etc. A programmer has to be very careful how and when it is changed, otherwise all kinds of bugs may occur.
In reality, most problems can be solved with commanding itself.
Specifically CanExecute property is more than enough.
I recommend this:
https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/data-binding/commanding?view=net-maui-7.0
Before becoming slave to manual changing bool variables.

Wicket 7 - AutoCompleted Text field - to have onSelect method

We would like to implement AutoCompleteTextField field, once user has selected the field from AutoComplete result, then system would auto populate on other text field, i have used the component AjaxFormComponentUpdatingBehavior (blur), however this will take effect on every text input from AutoCompleteTextField field, but if i change to AjaxFormComponentUpdatingBehavior (change), it doesnt work.
Below is the sample code:
AutoCompleteTextField<String> field_postcode = new AutoCompleteTextField<String>("field_postcode",
new PropertyModel<String>(getModelObject(), "wAdditionalInfo.postal"), autoCompleteRenderer) {
private static final long serialVersionUID = 1L;
#Override
protected Iterator<String> getChoices(String input) {
if (Strings.isEmpty(input)) {
List<String> emptyList = Collections.emptyList();
return emptyList.iterator();
}
List<String> choices = new ArrayList<String>();
List<Postcode> postcodeList = getProfileManager().findAllPostcodeByPostcode(input);
for (Postcode p : postcodeList) {
String postcode = p.getPostcode();
if (postcode.startsWith(input)) {
choices.add(p.getPostcode());
if (choices.size() == 10) {
break;
}
}
}
return choices.iterator();
}
};
field_postcode.setRequired(true);
field_postcode.add(new AjaxFormComponentUpdatingBehavior("blur"){
private static final long serialVersionUID=-1107858522700306810L;
#Override protected void onUpdate( AjaxRequestTarget target){
Postcode postcode = getProfileManager().findPostcodeByPostcode(field_postcode.getInput());
if (postcode != null) {
City city = postcode.getCity();
State state = city.getState();
field_city.setModelObject(city.getCity());
ddl_state.setModelObject(state);
if (isDisplayTip) {
//isDisplayTip true mean is from widrawal webform
isReadonly = true;
} else {
field_city.setEnabled(false);
}
ddl_state.setEnabled(false);
} else {
if (isDisplayTip) {
isReadonly = false;
} else {
field_city.setEnabled(true);
}
ddl_state.setEnabled(true);
}
target.add(field_city, ddl_state);
}
}
);
Is there any api from wicket to achieve this? We need to have something when user select the option from Auto complete, then it only onUpdate method of AjaxFormComponentUpdatingBehavior
According to https://github.com/apache/wicket/blob/cbc237159c4c6632b4f7db893c28ab39d1b40ed4/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js#L620 it should trigger change event on the HTMLInputElement and thus notify you on the server side.
Use the browser debugger to see whether https://github.com/apache/wicket/blob/cbc237159c4c6632b4f7db893c28ab39d1b40ed4/wicket-extensions/src/main/java/org/apache/wicket/extensions/ajax/markup/html/autocomplete/wicket-autocomplete.js#L453 is executed and whether it leads to an Ajax call with the value in the parameters.

Apache Wicket TextField

Good day!
I create some Table:
List<IColumn<User, String>> columns = new ArrayList<>();
columns.add(new AbstractColumn<User, String>(new Model<String>("")) {
#Override
public void populateItem(Item<ICellPopulator<User>> cellItem, String componentId, IModel<User> rowModel) {
cellItem.add(new Link<String>(componentId) {
#Override
public void onClick() {
System.out.println("editors" + rowModel.getObject().getName());
PageParameters parameters = new PageParameters();
parameters.add("id", rowModel.getObject().getId());
add(new EditPanel("panel", rowModel));
}
#Override
public IMarkupFragment getMarkup() {
return Markup.of("<div wicket:id='cell'> edit </div>");
}
});
}
When I click on cell into Table, cell markup "Edit", I create some Panel:
public class EditPanel extends Panel {
public EditPanel(String id, IModel<User> model) {
super(id, model);
User user = model.getObject();
if (user == null) {
user = new User();
}
List<UserRole> list = Arrays.asList(UserRole.values());
Form<?> form = new Form("form", new CompoundPropertyModel(user));
TextField<String> userName = new TextField<String>("name");
};
add(new FeedbackPanel("feedback"));
add(form);
form.add(userName);
}
}
How can I set value to
TextField userName = new TextField("name");
from my model, or if model == null, set any text what I need?
Thanks!
If you use Wicket 7 or older then you may use :
TextField<String> userName = new TextField<String>("name", new PropertyModel(model, "username"));
assuming that username is a property of User.
With Wicket 8.x you can use LambdaModel instead.
Heyy,
I think the problem is because you are passing the object and not the model.
The right way is passing with CompoundPropertyModel, like you do. It`s better then PropertyModel in this case.
Try doing this:
...
if (model.getObject() == null) {
model.setObject(new User());
}
Form<?> form = new Form("form", new CompoundPropertyModel(model));
...
Hope help you.

set property of new instance

thank you for helping.
First, I created a form with a (user defined) property.
as see below
public partial class nfrmtableitem : Form
{
private DataRow _datarow;
public DataRow U_Table_Row { get { return _datarow; } set { _datarow = value; } }
public nfrmtableitem()
{
InitializeComponent();
}
}
And I create second form with property as type of Form.
as see below
public partial class nftableshow : Form
{
private DataTable _datatable;
public DataTable U_DataTable { get { return _datatable; } set { _datatable = value; } }
private Form _inputform1;
public Form U_DGV_InputForm1 { get { return _inputform1; } set { _inputform1 = value; } }
}
when call it:
any where
nftableshow newfrmtableshow = new nftableshow()
{
Name = "newfrmtableshow",
Text = "Show the table",
MdiParent = this,
U_DGV_InputForm1 = new nfrmtableitem(),
};
newfrmtableshow.Show();
But I can not use the first form property in second form.
and the property is not in instance.
//the button in second form
private void button1_Click_Click(object sender, EventArgs e)
{
Form f1 = _inputform1 as Form;
/*
* {
* U_Table_Row = db.maindataset.Tables["customer"].NewRow(),
* };
*/
f1.Show();
}
Question:
How can I use the First form with specific (user defined) property in second form.
Regards
You should probably use dot notation to access the property of the first form. Try using
//the button in second form
private void button1_Click_Click(object sender, EventArgs e)
{
Form f1 = _inputform1 as Form;
{
f1.U_Table_Row = db.maindataset.Tables["customer"].NewRow(),
};
f1.Show();
}

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