WPF text binding from variable changing in separate class/namespace - c#

I am struggling with Text binding in my WPF app.
Lets imagine that I have another working app (ex. windows service) with some data in it.
In my WPF app I would like to have folder "DATA" with class where data are introduced and in same folder another class which would include a void which will query my windows service
I would like to show this data in my WPF window.
To make it simpler - one class with data, one class with data changing and WPF window with showing this data.
Unfortunately I can not achieve this... When I am executing below code, my window is showing 0 instead 123.
I would like to achive that my window will show value 123.
file "Database.cs" in folder "Data" in project "example"
namespace example.Data
{
public class Database
{
private int _testInt = 0;
public int testInt
{
get { return _testInt; }
set { _testInt = value; }
}
}
}
file "Query.cs" in folder "Data" in project "example"
namespace example.Data
{
public class Query
{
public Database _database;
public void execute()
{
_database = new Database();
_database.testInt = 123;
}
}
}
file "MainWindow.xaml.cs" in project "example"
namespace example
{
public partial class MainWindow : Window
{
public Data.Database _database;
public Data.Query _query;
public int testInt
{
get { return _database.testInt; }
set { _database.testInt = value; OnPropertyChanged(); }
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
_database = new Data.Database();
_query = new Data.Query();
_query.execute();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion
}
}
File MainWindow.xaml
<Window>
<TextBlock Text="{Binding testInt}"
Foreground="White"
FontSize="15"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="20,10,10,0" />
</Window>
P.S. If I will put
_database.testInt = 987;
to MainWindow.xaml.cs it is working properly - window is showing value 987 in textblock.

You have multiple instances of the Database object, a new one each time Query.execute is called and one in MainWindow constructor.
It's the data in the later that is displayed.
You should modify the content of this instance to see any change, for that, you must inject it in the Query object:
_query = new Data.Query(_database);
// ...
public class Query
{
private readonly Database _database;
public Query(Database database)
{
_database = database;
}
public void Execute()
{
_database.testInt = 123;
}
}
Finally you need a way to notify the view that the content as changed, that why Database should implement INotifyPropertyChanged.
But at this point it's badly named, because it's a model in the MVVM pattern.

you need to implement INotifyPropertyChanged
public partial class MainWindow : Window, INotifyPropertyChanged

from the MVVM view, I think these answers from Orace and Jason are on a good way, both do not solve the problem completely.
Let the Mainwindow implement INotifyPropertyChanged
Let the query accept the new value:
public void execute(int value)
{
//_database = new Database();
// inject _database like in the answer above
_database.testInt = value;
}
When your testInt changes, let the _query deliver the change down to the "database" (btw: you do it vice versa) See code below:
`public int testInt
{get { return _database.testInt; }
`set { _query.execute(value); OnPropertyChanged(); }`
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
_database = new Data.Database();
// the property change will change both the view and the model
testInt = 987;
}
Well, you have changed both model and view with one property change then, Good or not?!

Just for future users. There is small bug in Orace's answer: (It should be without "readonly" parameter, because below You are writing to it.
private Database _database;
public Query(Database database)
{
_database = database;
}

Related

Xaml bindings don't update (and everything seems like it should work) [duplicate]

This question already has an answer here:
Notify binding for static properties in static classes
(1 answer)
Closed 7 months ago.
I've been working on a unique kind of project for a while now and recently I've written a custom "binding system"(for external code) which works great, however today I needed to get some MVVM style bindings to work(for internal UI). After an entire day of googling and trying different things, I still don't have an answer or working code. I'm almost at a point where I'll just add "normal" bindings to my existing binding system and call it a day.
anyway... my question...
I'm trying to make a one-way binding from a ViewModel class to a UI element. There is are some "rules" I have to conform to though (like all (public) properties MUST be in a static class). At design-time everything works and VS can resolve the bindings (if the datacontext is set in xaml, NOT in cs). The bindings even update once to their default value at startup, but NOT when the property source changed.
TLDR;
read the bold text :)
Code:
[Public static class]
here the property is set by external code at runtime
public static class StaticClass
{
public static string ExampleProperty
{
get
{
return ViewModel.Instance.ExampleProperty;
}
set
{
if (ViewModel.Instance.ExampleProperty != value) ViewModel.Instance.ExampleProperty = value;
}
}
}
[ViewModel]
a singleton class that holds the non-static backing field for the static properties in the class above and implements INotifyPropertyChanged
internal class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private static ViewModel _instance = null;
internal static ViewModel Instance
{
get
{
if (_instance is null) _instance = new();
return _instance;
}
}
private static string _exampleProperty { get; set; } = "Pls work";
public string ExampleProperty
{
get
{
return _exampleProperty;
}
set
{
_exampleProperty = value;
OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (propertyName is not null) PropertyChanged?.Invoke(null, new(propertyName));
}
}
[Xaml example binding]
<Button Content="{Binding ExampleProperty, UpdateSourceTrigger=PropertyChanged}" Click="Button_Click"/>
[MainWindow.cs]
obviously a test project so this just changes the ExampleProperty to a random number on the Button.Click event
public partial class MainWindow : Window
{
Random random = new();
public MainWindow()
{
InitializeComponent();
this.DataContext = ViewModel.Instance;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
StaticClass.ExampleProperty = random.Next(0, 69).ToString();
}
}
so what am I doing wrong? Any help is greatly appreciated.
The expression
DataContext = new ViewModel();
assigns a different instance of the ViewModel class to the DataContext than the one returned from ViewModel.Instance, so that
StaticClass.ExampleProperty = random.Next(0, 69).ToString();
does not affect the DataContext. You should have assigned
DataContext = ViewModel.Instance;
Your ViewModel class does however not implement the singleton pattern correctly - it would have to avoid the creation of more than one instance, e.g. by declaring a private constructor.
The view does not need to use the singleton aspect of the view model at all. In order to access the current view model instance, cast the DataContext:
private void Button_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
ViewModel vm = (ViewModel)btn.DataContext;
vm.ExampleProperty = random.Next(0, 69).ToString();
}
Thanks to a comment on the question:
Also be aware that it is possible to bind directly to static properties of a static class, even with change notification, thus eliminating the need for a singleton. See e.g. here: stackoverflow.com/a/41823852/1136211
(and answer) I've had success with both a static and a non-static binding (FINALLY...).
For binding UI to a static class
The static class:
public static class StaticClass
{
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged;
#region Properties
public static string _exampleProperty = "Default value";
public static string ExampleProperty
{
get
{
return _exampleProperty;
}
set
{
if (_exampleProperty != value)
{
_exampleProperty = value;
OnStaticPropertyChanged();
}
}
}
#endregion
private static void OnStaticPropertyChanged([CallerMemberName]string propertyName = null)
{
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(propertyName));
}
}
How to bind to UI:
<TextBlock Text="{Binding Path=(local:StaticClass.ExampleProperty)}"/>
How to set the property:
StaticClass.ExampleProperty = "New value that automatically updates the UI :)";
For binding UI to a non-static class
Use the code from the other answer.

Change ViewModel from Service WPF

I am learning to create a WPF application following the MVVM patern. I'm try change data in viewmodel from service class but it can work, here is example code:
In MainWindow.xaml:
<Grid Grid.Row="6">
<TextBox materialDesign:HintAssist.Hint="Status"
Text="{Binding Status, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
VerticalAlignment="Center" />
</Grid>
In MainViewModel.cs:
public class MainViewModel : BaseViewModel
{
private static MainViewModel _instance = new MainViewModel();
public static MainViewModel Instance { get { return _instance; } }
//...
// Status
private string _Status = "Status";
public string Status { get => _Status; set { _Status = value; OnPropertyChanged(); } }
public MainViewModel()
{
////
// => This command can change status
// Start
StartCommand = new RelayCommand<object>((p) => { return true; }, (p) =>
{
OutStatus("Task success!");
});
}
public void OutStatus(string status)
{
Status = status;
}
}
In UtilitiesService.cs
public static class UtilitiesService{
public static void SetStatus(){
// => Here i can't change Status and can't binding to MainWindow.xaml
MainViewModel.Instance.OutStatus("Change Status in service");
}
}
So how can I change a property in manviewmodel in service file.Sorry Im so noob :))
You are using different instances of MainViewModel for data binding and for updating.
Also don't use public static instances or members across the application. Instead directly pass around the instance (in your case MainViewModel and UtilitiesService).
Generally static class members like properties or fields introduce a potential memory leak, because the garbage collector can't collect them to free memory. It also makes unit testing difficult and defies the concept of object oriented language key features like encapsulation. It will make code hard to modify.
In the simplest scenario, you can create the MainViewModel instance in your MainWindow. You can also create a shared instance of UtilitiesService at this point as well.
It's unclear what purpose UtilitiesService has. If it is meant to update MainViewModel by other View Model classes you can do it your way. If it is meant to be used in the Model, then you shouldn't do it your way. In this case your MainVoewModel would listen to the UtilitiesService events to update itself. Because in MVVM the Model does never talk to the View Model.
The recommended C# naming convention suggests to name fields using the camelCase pattern (starting with a lower case letter). Microsoft Docs: Naming Guidelines
A TextBox.Text binding that is configured to bind OneWay is pretty useless. In this case the TextBox only serves as display. You should then use TextBlock instead.
MainViewModel.cs
public class MainViewModel : BaseViewModel
{
//...
// Status
private string _status = "Status";
public string Status { get => _status; set { _status = value; OnPropertyChanged(); } }
public MainViewModel()
{
////
// => This command can change status
// Start
StartCommand = new RelayCommand<object>((p) => { return true; }, (p) =>
{
SetStatus("Task success!");
});
}
public void SetStatus(string status)
{
Status = status;
}
}
UtilitiesService.cs
public class UtilitiesService
{
private MainViewModel MainViewModel { get; }
public void UtilitiesService(MainViewModel mainViewModel)
{
this.MainViewModel = mainViewModel;
}
public void SetStatus()
{
// Change MainViewModel.Status and update bindings in MainWindow.xaml
this.MainViewModel.SetStatus("Change Status in service");
}
}
MainWindow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var mainViewModel = new MainViewModel();
this.DataContext = mainViewModel;
var sharedUtilitiesService = new UtilitiesService(mainViewModel);
// Pass the shared UtilitiesService instance to other view model classes
// to allow them to update the MainViewModel anonymously.
var otherViewModel = new OtherViewModel(sharedUtilitiesService);
}
}
MainWindow.xaml
<Window>
<TextBlock Text="{Binding Status}" />
</Window>

best practice to pass parameters between open pages

I'm developing a Windows application (UWP) that has two pages, I want the best practice to pass parameters between pages.
it's my scenario:
We have two pages, each open and remain at the middle of the screen and a Button on each page, which send the message to the other page when we click on it.
I also want to pass information continuously and repeatedly.
in Page1.cs:
Page2 page2;
public Page1()
{
this.InitializeComponent();
CreatPage2();
}
// creat page 2
private async void CreatPage2()
{
var NewWindow = CoreApplication.CreateNewView();
int NewWindowid = 0;
await NewWindow.Dispatcher.RunAsync(CoreDispatcherPriority.High, () =>
{
Frame newframe = new Frame();
newframe.Navigate(typeof(Page2), this);
Window.Current.Content = newframe;
Window.Current.Activate();
ApplicationView.GetForCurrentView().Title = "page2";
NewWindowid = ApplicationView.GetForCurrentView().Id;
});
await Windows.UI.ViewManagement.ApplicationViewSwitcher.TryShowAsStandaloneAsync(NewWindowid);
}
//Button
private void ChangeP2_Click(object sender, RoutedEventArgs e)
{
// send a message to the texblock in the page2
page2.TexBlock2.Text=$"From page1 :{e.ToString()}";
// change text color of the texblock in the page2
page2.Foreground= new SolidColorBrush(Windows.UI.Colors.Red);
}
in Page2.cs:
Page1 page1;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
page1 = e.Parameter as Page1;
base.OnNavigatedTo(e);
}
public Page2()
{
this.InitializeComponent();
}
//Button
private void ChangeP1_Click(object sender, RoutedEventArgs e)
{
// send a message to the texblock in the page1
page1.TexBlock1.Text=$"From page2 :{e.ToString()}";
// change text color of the texblock in the page1
page1.Foreground= new SolidColorBrush(Windows.UI.Colors.Red);
}
the above code just work for the page2 to the page1. (it can change the textblock of pagea).
Please help me, I can't find a solution that work on two pages
Naah… the best way is to use a standard pattern that consist of an app ViewModel class, which contains all the common app data that you want to use in the logic layer.
I always do it like this:
1) I use the MainPage automatically created as the "shell" of the app, with a property that is the AppViewModel.
The MainPage (and thus the AppViewModel) can be accessed from everywhere in the app, by setting itself as a static field in its own class.
This is the code, simpler than you think:
public sealed partial class MainPage : Page
{
public AppViewModel ViewModel { get; set; } = new AppViewModel();
public static MainPage Current { get; set; }
public MainPage()
{
this.InitializeComponent();
Current = this;
}
}
2) The AppViewModel itself is a class that must implement the INotifyPropertyChanged interface, in order to enable bindable properties and functions.
It is common, among developers, to create a base class that implements it and then derive all the classes that needs bindable properties from it.
Here it is:
public class BaseBind : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null) =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
protected bool SetProperty<T>(ref T storage, T value,
[CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
}
Then you derive AppViewModel class (and all the other model and viewmodel classes) from it… populating it with all the common properties that you need to share across pages.
I have even added a derived property, in order to show how you can share even multiple data types at once, and a function:
public class AppViewModel : BaseBind
{
public AppViewModel()
{
// ...
}
// All common app data
private string sampleCommonString;
public String SampleCommonString
{
get { return sampleCommonString; }
set { SetProperty(ref sampleCommonString, value); OnPropertyChanged(nameof(SampleDerivedProperty1)); OnPropertyChanged(nameof(SampleDerivedProperty2)); }
}
public String SampleDerivedProperty1 => "return something based on SampleCommonString";
public String SampleDerivedProperty2
{
get
{
<<evaluate SampleCommonString>>
return "Same thing as SampleDerivedProperty1, but more explicit";
}
}
// This is a property that you can use for functions and internal logic… but it CAN'T be binded
public String SampleNOTBindableProperty { get; set; }
public void SampleFunction()
{
// Insert code here.
// The function has to be with NO parameters, in order to work with simple {x:Bind} markup.
// If your function has to access some specific data, you can create a new bindable (or non) property, just as the ones above, and memorize the data there.
}
}
3) Then, in order to access all this from another Page, just create an AppViewModel field in that page, as seen below:
public sealed partial class SecondPage : Page
{
public AppViewModel ViewModel => MainPage.Current.ViewModel;
public SecondPage()
{
this.InitializeComponent();
}
}
...and you can easily bind XAML controls properties to the AppViewModel itself:
<TextBlock Text="{x:Bind ViewModel.SampleCommonString, Mode=OneWay}"/>
<Button Content="Sample content" Click="{x:Bind ViewModel.SampleFunction}"/>
(Mode=OneWay is for real-time binding, in order that the property is immediately updated even in the UI, while Mode=TwoWay is used for those properties that can be edited from the control itself, by the user, in order to interact with app logic).
Hope this helped.
Best regards and happy new year.

Bubbling NotifyPropertyChanged

According to this answer I should not need to bother about NotifyPropertyChanges Bubbling up the hierachie, still I can't get it to work with a (simplified test-) structure like that:
a Data-Holding Class
public class TestNotifyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _Test = "default";
public string Test
{
get
{
return _Test;
}
set
{
if(_Test!=value)
{
_Test = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Test"));
}
}
}
}
A ViewModel that used that Test-Class and Test-Property:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestNotifyChanged tnc = new TestNotifyChanged(); // only to init, otherwise VS screams at me
public ViewModel(TestNotifyChanged tnc)
{
tnc = tnc; // getting an instance of TestNotifyChanged from "Master" passed in, which hopefully will be replaces by a singleton class.
}
private string _Test;
public string Test
{
get
{
return tnc.Test; // this might be the crucial part!?
}
set
{
if (_Test != value) // never hits that, as I would expect, but you never know..
{
_Test = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Test")); // of course also never hit, as expected
}
}
}
}
And finally my MainWindow cs
public partial class MainWindow : Window
{
TestNotifyChanged tnc;
public MainWindow()
{
InitializeComponent();
tnc = new TestNotifyChanged();
DataContext = new ViewModel(tnc); // pass in my Test-Object that has the Values.
}
private void ButtonGet_Click(object sender, RoutedEventArgs e)
{
tnc.Test = "new Value";
MessageBox.Show($"{tnc.Test}"); // got "new Value" here!
}
}
And in xaml I have besides that one button a simple TextBlock that is bound to the ViewModel's Test Property:
<TextBlock x:Name="OutputId" Text="{Binding Path=Test, Mode=OneWay}"/>
What is happening now:
The default value "default" is shown in TextBlock.
When I click the button the messageBox shows the "new Value"
TextBlock is not updating to "new Value"
What I want to achieve:
seems easy: TextBlock should update to "new Value"
I can easily make this work when I directly set the Test Value on the ViewModel - but this doesn't seem right and is far away from what I thought I could structure my app/code. The future goal is to have a Singleton (static won't work I figured out) "RecordStore" that has most of the data (and gets it from an API, from local Database, or just from Memory if any of these are done)
So the question is:
Why is the NotifyPropertyChange not bubbling up to the View/ViewModel?
Or is there another issue I don't see?
I've read INotifyPropertyChanged bubbling in class hierarchy
and
What is a good way to bubble up INotifyPropertyChanged events through ViewModel properties with MVVM?
and
https://learn.microsoft.com/en-us/dotnet/framework/winforms/how-to-implement-the-inotifypropertychanged-interface
and
OnPropertyChange called but not taking any effect on UI
most of those questions are also quite old...
EDIT:
I tried #MineR 's suggestion that way:
// made tnc public in ViewModel
public TestNotifyChanged tnc = new TestNotifyChanged();
// changed Binding directly to that (and it's Property):
<TextBlock x:Name="OutputId" Text="{Binding Path=tnc.Test, Mode=OneWay}"/>
Unfortunately now I don't even get the default, so I must have misunderstood smth.
EDIT2:
I did one thing wrong in the 1st edit:
// this isn't recognized as bindable parameter:
public TestNotifyChanged tnc = new TestNotifyChanged();
// it instead has to be
public TestNotifyChanged tnc { get; }
And I made it TNC, removed the local Test parameter, bound directly to Path=TNC.Test
So I understood, that PropertyChanges do not bubble up the way I hoped/thought, it's better to bind directly down to the nested object.
"Bubbling" is a concept of routed events. A regular event like PropertyChanged doesn't "bubble up".
Besides the apparent bug tnc = tnc; in the ViewModel (which should be this.tnc = tnc;) the Test properties of the two classes are unrelated. In order to update its own Test property, ViewModel must register a PropertyChanged event handler at tnc. And it must update the property of tnc when its own Test property changes.
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestNotifyChanged tnc;
public ViewModel(TestNotifyChanged t)
{
tnc = t;
tnc.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Test) || string.IsNullOrEmpty(e.PropertyName))
{
Test = tnc.Test; // update ViewModel.Test from TestNotifyChanged.Test
}
};
}
private string test;
public string Test
{
get
{
return test; // always return own value
}
set
{
if (test != value)
{
test = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Test)));
tnc.Test = Test; // update TestNotifyChanged.Test from ViewModel.Test
}
}
}
}
Alternatively, drop the Test property's backing field and only operate on tnc.Test:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestNotifyChanged tnc;
public ViewModel(TestNotifyChanged t)
{
tnc = t;
tnc.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Test) || string.IsNullOrEmpty(e.PropertyName))
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Test)));
}
};
}
public string Test
{
get { return tnc.Test; }
set { tnc.Test = Test; }
}
}
Fortunately, it is not necessary at all.
There could instead just be a public Tnc property like
public class ViewModel
{
public TestNotifyChanged Tnc { get; }
public ViewModel(TestNotifyChanged tnc)
{
Tnc = tnc;
}
}
with a Binding like this:
<TextBlock Text="{Binding Tnc.Test}"/>

UWP MVVM Data Binding for dummies (textbox.text from String)

Well, having a go at MVVM with UWP template 10. I have read many pages, and although everyone tries to say its really easy, I still can't make it work.
To put it into context, OCR is being run on an image, and I would like the text to be displayed in textbox automatically.
Here is my Model:
public class TextProcessing
{
private string _ocrText;
public string OcrText
{
get { return _ocrText; }
set
{
_ocrText = value;
}
}
}
Here is my ViewModel:
public class ScanPageViewModel : ViewModelBase, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TextProcessing _ocrTextVM;
public ScanPageViewModel()
{
_ocrTextVM = new TextProcessing();
}
public TextProcessing OcrTextVM
{
get { return _ocrTextVM; }
set {
_ocrTextVM = value;
this.OnPropertyChanged("OcrTextVM");
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
Here is my View:
<TextBox x:Name="rtbOcr"
Text="{Binding OcrTextVM.OcrText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Firstly, that is not working. Could someone try to show where I am going wrong?
Then, the data is coming from a Services file, how would the Services update the value? What would be the correct code?
Thanks in advance.
Following code is cite from code.msdn (How to achieve MVVM design patterns in UWP), it will be helpful for you:
Check you code step by step.
1.ViewModel implemented interface INotifyPropertyChanged,and in property set method invoked PropertyChanged, like this:
public sealed class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _productName;
public string ProductName
{
get { return _productName; }
set
{
_productName = value;
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(nameof(ProductName)));
}
}
}
}
2.Initialize you ViewMode in you page, and set DataContext as the ViewMode, like this:
public sealed partial class MainPage : Page
{
public MainPageViewModel ViewModel { get; set; } = new MainPageViewModel();
public MainPage()
{
...
this.DataContext = ViewModel;
}
}
3.In you xaml, binding data from viewMode, like this:
<TextBox Text="{Binding Path=ProductName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Name="ProductNameTextBox" TextChanged="ProductNameTextBox_TextChanged" />
Your OnPropertyChanged call on OcrTextVM isn't actually called in your case, since you set the value in the constructor to its backing field and bypass the property.
If you set the value via the property, it should work:
public ScanPageViewModel()
{
OcrTextVM = new TextProcessing();
}
Of course your view needs to know that ScanPageViewModel is its DataContext. Easiest way to do it is in the constructor of the code-behind of your view:
public OcrView()
{
DataContext = new ScanPageViewModel();
InitializeComponent();
}
Assuming your OCR service is returning a new TextProcessing object on usage, setting the property of OcrTextVM should suffice:
public class ScanPageViewModel : ViewModelBase, INotifyPropertyChanged
{
//...
private void GetOcrFromService()
{
//...
TextProcessing value = OcrService.Get();
OcrTextVM = value;
}
}
On a note, the OcrTextVM name doesn't really reflect what the property is doing, since it doesn't look like it's a viewmodel. Consider renaming it.
Actually, it is very easy once I manage to understand. Here is the code needed to update a TextBox.Text
In the Models:
public class DisplayText : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
}
}
}
In the XAML file:
<TextBox Text="{Binding Helper.Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ... />
In the ViewModels:
private DisplayText _helper = new DisplayText();
public DisplayText Helper
{
get { return _helper; }
set
{
_helper = value;
}
}
Then any mod from the ViewModels:
Helper.Text = "Whatever text, or method returning a string";

Categories

Resources