C
C#17mo ago
Mohammed85

Would like to access the value of the Elements from my view model any ideas

9 Replies
Vi Ness
Vi Ness17mo ago
In MVVM, your ViewModel usually doesn't know anything about your View, includes the elements in it. To sync up your properties, you bind to them in your View like this
<TextBox Text="{Binding Username}"/>
<TextBox Text="{Binding Username}"/>
And in your ViewModel you have public properties that raise the PropertyChanged event to let the View know when to update. Since it looks like you're using ReactiveUI, it would look something like this
private string _username;
public string Username
{
get => _username;
set => RaiseAndSetIfChanged(ref _username, value);
}
private string _username;
public string Username
{
get => _username;
set => RaiseAndSetIfChanged(ref _username, value);
}
The command for your button will be made in a similar way. You can read about binding to commands in Avalonia with ReactiveUI here: https://docs.avaloniaui.net/docs/next/guides/data-binding/how-to-bind-to-a-command-with-reactiveui
How to Bind to a Command with ReactiveUI | Avalonia UI
This guide shows you how to bind a view model method (that performs an action) to a control that can initiate an action in response to user interaction (for example, a button). This binding is defined in XAML using the Command attribute, for example:
Mohammed85
Mohammed85OP17mo ago
OHHH thanks
Mohammed85
Mohammed85OP17mo ago
@vi.ness ?
Vi Ness
Vi Ness17mo ago
Oh, you might need to change to this.RaiseAndSetIfChanged(ref _email, value); I haven't used ReactiveUI in a while
Mohammed85
Mohammed85OP17mo ago
No just needed to do it like this thanks for your time
Mohammed85
Mohammed85OP17mo ago
it is imported by defult i do not really use it
Vi Ness
Vi Ness17mo ago
That does create public properties but because there is no PropertyChanged event, the binding will only work from View to ViewModel. This is prob'ly fine for what you're doing now but if you want to reset the text from your ViewModel later, it won't update in the View.
Mohammed85
Mohammed85OP17mo ago
Oh okay thanks for the infromation but as you said for my work this is completely fine.
Want results from more Discord servers?
Add your server