I'm learning to create an app for WP7 (Mango), and somehow having this problem.
This is not actual code to my app, but a simplified version of the same problem. I think mostly it's due to lack of deep understanding of how binding works.
XAML.
<TextBlock x:Name="PageTitle" Text="{Binding Title}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
Code Behind.
private MainPageViewModel viewModel;
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
viewModel = new MainPageViewModel();
this.DataContext = viewModel;
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
viewModel.GenerateTitle();
}
And my ViewModel.
private static int counter = 0;
private string title;
public string Title
{
get { return title; }
set
{
if (title != value)
{
title = value;
OnPropertyChanged("Title");
}
}
}
public MainPageViewModel()
{
title = "Init";
}
public void GenerateTitle()
{
if (counter == 0)
title = "0"; // Title = "0" will work fine.
if (counter == 1)
title = "1";
counter++;
}
Problem is, it only update the binding once inside my ViewModel constructor, so the title is "Init".
Any call to the GenerateTitle does not update the property. It works if I use 'Title' instead of 'title', which calls the setter.
Or I should really use 'Title'? I haven't done much C#, so my understanding of OOP is not that great yet.
The following line in the setter is what notifies the observers that he value has changed:
OnPropertyChanged("Title");
When you use the private field value, that method isn't being called so the observers aren't being notified that the value of the property has changed.
Because of that, you need to use the Property if you want the observers to be notified. You could also add the OnPropertyChanged("Title"); line to your GenerateTitle() method, but I would recommend just using the Property.
Yes you have to use Title as title just sets the field whereas Title runs the setter which raises the event
Related
I have a noob problem. As the title says, I'm having a problem with an observable collection.
I'm trying to fill a collection passing a value trough a TextBox, and then adding it to an observable collection. When I press the button "Add Ciudad", a TextBox to insert the new value and a button to save it is displayed.
The value gets successfully to the method in charge of doing that ("Add Input City"), but the UI never shows the new item.
By the way, the first value added manually in "Load Ciudades" shows properly.
I saw some related questions, but still I'm not able to solve the problem.
I suspect I'm not properly adding the items. For more trouble, I'm a completely noob with C# :D.
Here's the code so you can judge:
Cities model:
public class Ciudad : INotifyPropertyChanged
{
private string nombre;
public String Nombre
{
get { return nombre; }
set {
nombre = value;
RaisePropertyChanged("Nombre");
RaisePropertyChanged("Ciudades"); //Dunno if this one is necesary.
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
Cities view model:
public ObservableCollection<Ciudad> Ciudades { get; } = new ObservableCollection<Ciudad>();
public void LoadCiudades()
{
Ciudades.Add(new Ciudad { Nombre = "Random city" });
}
public void AddInputCity(string new_city)
{
Ciudades.Add(new Ciudad { Nombre = new_city });
}
Cities view:
<Grid>
<DataGrid ItemsSource = "{ Binding Path = Ciudades, UpdateSourceTrigger=PropertyChanged }" Name="DGrid">
</DataGrid>
<Button Click="Button_Click" Height="30" Width="150" Margin="0,250,0,0">Add Ciudad</Button></Grid>
Cities view cs
TextBox iTextBox;
public CiudadesView()
{
InitializeComponent();
}
private void Add_Input_Text()
{
TextBox iText = new TextBox
{
Name = "iText",
Width = 250,
Margin = new Thickness(100)
};
Button saveBtn = new Button()
{
Content = "Save"
};
saveBtn.Click += new RoutedEventHandler(Button_Save_Click);
sPanel.Children.Add(iText);
sPanel.Children.Add(saveBtn);
iTextBox = iText;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Add_Input_Text();
}
private void Button_Save_Click(object sender, RoutedEventArgs e)
{
string ciudadNuevoNombre = iTextBox.Text;
CiudadesViewModel viewModel = new CiudadesViewModel();
viewModel.AddInputCity(ciudadNuevoNombre);
}
Any ideas or suggestions?
Thank you all! : )
Make sure that you call the AddInputCity method of the existing view model instance in your Button_Click event handler, e.g.:
private void Button_Click(object sender, RoutedEventArgs e)
{
var viewModel = DataContext as YourViewModelClass;
if (viewModel != null)
viewModel.AddInputCity("new...");
}
You've not shown us your click code and several other things like the relationship between view and viewmodel.
I suggest you also take a look at binding commands rather than click handlers.
This is an article intended to introduce the reader to MVVM which adds an item to a bound observablecollection using a command:
https://social.technet.microsoft.com/wiki/contents/articles/32164.wpf-mvvm-step-by-step-2.aspx
I am having a little bit of trouble getting a ProgressBar to work. When I start it up, nothing happens and I can't see why?
I thought that this would start the task worker.RunWorkerAsync();
The below example should be able to be copied and pasted into a new solution and be run for testing if needed.
The XAML,
<Grid Margin="20">
<ProgressBar
Height="60"
Minimum="0"
Maximum="100"
Value="{Binding Progress, Mode=OneWay}"
Visibility="{Binding ProgressVisibility}"/>
</Grid>
My code,
public partial class MainWindow : Window
{
public ProggressbarViewModel PsVm { get; set; }
public MainWindow()
{
InitializeComponent();
PsVm = new ProggressbarViewModel();
}
public class ProggressbarViewModel
{
public ProggressbarViewModel()
{
var worker = new BackgroundWorker();
worker.DoWork += DoWork;
worker.ProgressChanged += ProgressChanged;
worker.RunWorkerAsync();
}
private int _progress;
public int Progress
{
get { return _progress; }
set
{
if (_progress == value) return;
_progress = value;
OnPropertyChanged();
}
}
private void DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
_progress = i;
OnPropertyChanged();
}
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress = e.ProgressPercentage;
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Any help would be much appreciated.
EDIT: The question is is similar possibly a duplicate in that sense, however the linked answer did not solve my problem, like it states in the Duplicate banner.
When you're not explicitly indicating source object for your bindings (by means of Binding.Source or Binding.RelativeSource properties), the framework uses (possibly inherited) value of DataContext of the target object as the source. The problem is that you don't assign your view-model to the DataContext property of any control. Thus, the source for the bindings resolves to null and nothing is showing on your progress bar.
To resolve your issue you should assign your view model to the DataContext of your MainWindow:
public MainWindow()
{
InitializeComponent();
PsVm = new ProggressbarViewModel();
DataContext = PsVm;
}
If however you're planning on using different DataContext for your window, you can bind DataContext of ProgressBar:
<ProgressBar
DataContext="{Binding Path=PsVm,
RelativeSource={RelativeSource AncestorType=local:MainWindow}}"
(...) />
You could also modify particular bindings by prepending PsVm. to the value of Path and using RelativeSource, e.g.:
Value="{Binding Path=PsVm.Progress,
RelativeSource={RelativeSource AncestorType=local:MainWindow},
Mode=OneWay}"
In that case however you'd have to modify each binding, so previous solutions are quicker and/or simpler.
As a side note, you might also want to change the way you're reporting progress - note that OnPropertyChanged in your DoWork method is not called from UI thread. The proper way to do it would be:
private void DoWork(object sender, DoWorkEventArgs e)
{
var worker = (BackgroundWorker)sender;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
worker.ReportProgress(i); //This will raise BackgroundWorker.ProgressChanged
}
}
Also, in order to support progress reporting, you should set WorkerReportsProgress to true on your worker, e.g.:
var worker = new BackgroundWorker { WorkerReportsProgress = true };
I have simplified app to show my issue
When I click button, it changes Text property of ViewModel and TextBlock.Text is updated.
MainPage.xaml
<StackPanel>
<Button Click="ButtonBase_OnClick">Button to change text</Button>
<TextBlock Text="{x:Bind ViewModel.Text, Mode=OneWay}"></TextBlock>
</StackPanel>
MainPage.xaml.cs
public MainPage()
{
ViewModel = new ViewModel();
this.InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
ViewModel.Text = "x:Bind works";
}
ViewModel class has one string property (Text) and implemented INotifyPropertyChange interface.
Problem starts when ViewModel is not set in ctor (i.e. viewModel is null and changed in runtime):
public MainPage()
{
//ViewModel = new ViewModel();//this line has been removed
this.InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
ViewModel = new ViewModel();//this line has been added
ViewModel.Text = "x:Bind does not work";
}
Complited binding is not working (Text is not changed) and I could not figure out why it is so... I need to change viewModel from null (vm is null because it is waiting for some data in real app)
{x:Bind} bindings (often referred-to as compiled bindings) uses generated code to achieve its benefits. At XAML load time, {x:Bind} is converted into what you can think of as a binding object, and this object gets a value from a property on a data source. These generated code can be found in your obj folder, with names like (for C#) <view name>.g.cs.
For your code, the generated code will like following:
// Update methods for each path node used in binding steps.
private void Update_(global::UWP.BlankPage3 obj, int phase)
{
if (obj != null)
{
if ((phase & (NOT_PHASED | DATA_CHANGED | (1 << 0))) != 0)
{
this.Update_ViewModel(obj.ViewModel, phase);
}
}
}
private void Update_ViewModel(global::UWP.ViewModel obj, int phase)
{
this.bindingsTracking.UpdateChildListeners_ViewModel(obj);
if (obj != null)
{
if ((phase & (NOT_PHASED | DATA_CHANGED | (1 << 0))) != 0)
{
this.Update_ViewModel_Text(obj.Text, phase);
}
}
}
...
private global::UWP.ViewModel cache_ViewModel = null;
public void UpdateChildListeners_ViewModel(global::UWP.ViewModel obj)
{
if (obj != cache_ViewModel)
{
if (cache_ViewModel != null)
{
((global::System.ComponentModel.INotifyPropertyChanged)cache_ViewModel).PropertyChanged -= PropertyChanged_ViewModel;
cache_ViewModel = null;
}
if (obj != null)
{
cache_ViewModel = obj;
((global::System.ComponentModel.INotifyPropertyChanged)obj).PropertyChanged += PropertyChanged_ViewModel;
}
}
}
Here I just copy some method that related to your issue. From these method, you can find that before update TextBlock or PropertyChanged listeners, it will check if the ViewModel is null. If it is null, nothing will be done. So to make {x:Bind} work, we must initialize ViewModel before page loaded. And this is the reason why {x:Bind} doesn't work when you initialize ViewModel in Button.Click event.
To fix this issue, you can implement INotifyPropertyChanged interface for ViewModel like Filip said so that the generated code can be notified when ViewModel changed (from null to new ViewModel()) and update you UI.
But I think you can just initialize ViewModel in constructor. When you initialize ViewModel, you can set the properties that you are waiting for to null first like:
public MainPage()
{
ViewModel = new ViewModel() { Text = null };
this.InitializeComponent();
}
And then update these properties when your date is ready. In this way, you can do not implement INotifyPropertyChanged interface on your page.
Besides these, there is another cheaper way, you can call this.Bindings.Update(); method to force the bindings to be updated after you initialize ViewModel like following:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
ViewModel = new ViewModel();
ViewModel.Text = "x:Bind does not work";
this.Bindings.Update();
}
Did you implement INotifyPropertyChanged on page like so
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
private ViewModel viewModel;
public ViewModel ViewModel
{
get { return viewModel; }
set
{
viewModel = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ViewModel)));
}
}
public MainPage()
{
ViewModel = new ViewModel { };
this.InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
ViewModel = new ViewModel { };//this line has been added
ViewModel.Text = "x:Bind does not work";
}
public event PropertyChangedEventHandler PropertyChanged;
}
This works for me.
I am trying to implement data binding, and to have TextBox's text to be update once I click on some button.
XAML:
<TextBox Text="{Binding Path=Output}" />
Code:
public MainWindow()
{
InitializeComponent();
DataContext = Search;
Search.Output = "111";
}
public SearchClass Search = new SearchClass();
private void button1_Click(object sender, RoutedEventArgs e)
{
Search.Output = "222";
}
public class SearchClass
{
string _output;
public string Output
{
get { return _output; }
set { _output = value; }
}
}
When I execute the program, I see "111", so the binding from MainWindow() works, but if I click a button - the text in the TextBox is not updated (but in the debugger I see that button1_Click is executed and Search.Output is now equal to "222"). What am I doing wrong?
You should implement INotifyPropertyChanged in your SearchClass and then in setter raise the event:
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string Output
{
get { return _output; }
set
{
_output = value;
PropertyChanged(this, new PropertyChangedEventArgs("Output"));
}
}
If I understood right, SearchClass is the DataContext for your TextBlock. In this case implementing as above would help.
When WPF see some class as the source of Binding - it tries to cast it to INotifyPropertyChanged and subscribe to PropertyChanged event. And when event is raised - WPF updates the binding associated with sender (first argument of PropertyChanged). It is the main mechanism that makes binding work so smoothly.
You have to implement the INotifyPropertyChanged interface on your SearchClass class. This is how binder values are notified their source values have changed. It displays the "111" value because it hasn't been laid out yet (more or less), but will won't update after that until you implement that interface.
say I have this control:
public partial class bloc999 : UserControl
{
bloc999Data mainBlock = new bloc999Data();
public bloc999()
{
InitializeComponent();
mainBlock.txtContents = "100";
base.DataContext = mainBlock;
}
}
in the xaml:
<TextBox Margin="74,116,106,0" Name="txtContents"
Text="{Binding Path=txtContents, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" />
<TextBox Margin="74,145,106,132" Name="txtContents2"
Text="{Binding Path=txtContents2, UpdateSourceTrigger=PropertyChanged,Mode = TwoWay}" />
Then I have this class:
public class bloc999Data : INotifyPropertyChanged
{
string _txtContents;
string _txtContents2;
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
public string txtContents2
{
get
{
return this._txtContents2;
}
set
{
if (int.Parse(value) > int.Parse(this._txtContents))
{
this._txtContents2 = "000";
}
else
this._txtContents2 = value;
NotifyPropertyChanged("txtContents2");
}
}
public string txtContents
{
get
{
return this._txtContents;
}
set
{
this._txtContents = value;
NotifyPropertyChanged("txtContents");
}
}
}
Ok now say I have A button on the form and I do this in the code:
mainBlock.txtContents2 = "7777777";
It puts 000 in the textbox, but If i just type in manually, in the textbox (txtContents2), the setter code is called but for some reason the textboxes value does not change, the instance value does change. help?
I believe it's just because the value is changing within the context of the data binding operation, so WPF just ignores it because it knows the value is changing and thinks the event is superfluous. What it doesn't know is that you've gone and changed the value from the value WPF has to something else again.
If you do the notification in a separate message then WPF will process it outside the context of the current data binding operation and will thus pick up the change:
if (int.Parse(value) > int.Parse(this._txtContents))
{
this._txtContents2 = "000";
// notify WPF of our change to the property in a separate message
Dispatcher.BeginInvoke((ThreadStart)delegate
{
NotifyPropertyChanged("txtContents2");
});
}
else
{
this._txtContents2 = value;
NotifyPropertyChanged("txtContents2");
}
This assumes your view model has access to the Dispatcher. An example of how to do so is shown in my blog post on a base ViewModel class.
I was having similar problem earlier here
In your usercontrol, update Binding and set UpdateSourceTrigger to Explicit
<TextBox Margin="74,145,106,132" x:Name="txtContents2" TextChanged="txtContents2_TextChanged"
Text="{Binding Path=txtContents2, UpdateSourceTrigger=Explicit,Mode = TwoWay}" />
then in the TextChanged event handler update the binding manually by validating the input.
move validation logic from property txtContent2's setter in bloc999Data in this event handler
private void txtContents2_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.Parse(txtContents2.Text) > int.Parse(mainBlock.txtContents))
{
mainBlock.txtContents2 = "000";
txtContents2.GetBindingExpression(TextBox.TextProperty).UpdateTarget();
}
else
{
mainBlock.txtContents2 = txtContents2.Text;
txtContents2.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
}
and it works.
Hope it helps!!