Why my binding does not work? - silverlight

Have class behine the xaml that contain the propertie 'Int32 Count'
I want to bind some TextBlock to the 'Count' value - that the TextBlock.Text will have the value of the 'Count'.
So i wrote in the xaml :
<TextBlock Text="{ Binding Path=Count }" />
And in the code behind the xaml i add to the constructor:
DataContext = this;
But each change of the 'Count' does not change the text of the TextBlock.
The code of 'Count'
Int32 count;
public Int32 Count
{
get
{
return count;
}
set
{
count = value;
}
}

place the INotifyPropertyChanged interface to your class:
public class MainPage : INotifyPropertyChanged
{
}
then implement:
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyname)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyname));
}
what this does if provide the mechanism for notifying the view that something has changed in your datacontext and you do it like this:
public Int32 Count
{
get
{
return count;
}
set
{
count = value;
OnPropertyChanged("Count"); //This invokes the change
}
}
But of course, i recommend that you separate design and code using the MVVM pattern. This way, you can implement the propertychanged to a ViewModelBase class, then inherit that for each of your ViewModels.

You should ensure your DataContext implements INotifyPropertyChanged. Then you have to fire the property change events properly.

Related

How can I RaisePropertyChanged on property change?

Here I added a model to my viewmodel:
public dal.UserAccount User {
get
{
return _user;
}
set
{
_user = value;
RaisePropertyChanged(String.Empty);
}
}
I handle property change event...
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
This is the binding I use:
<TextBox Text="{Binding User.firstname, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />
Why the propertychange event is not triggered on updating view?
PropertyChanged is used to notify the UI that something has been changed in the Model.
Since you're changing an inner property of the User object - the User property itself is not changed and therefore the PropertyChanged event isn't raised.
Second - your Model should implement the INotifyPropertyChanged interface. - In other words make sure UserAccount implements INotifyPropertyChanged, otherwise changing the firstname will not affect the view either.
Another thing:
The parameter RaisePropertyChanged should receive is the Name of the property that has changed. So in your case:
Change:
RaisePropertyChanged(String.Empty);
To
RaisePropertyChanged("User");
From MSDN:
The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.
(No need to refresh all the Properties in this case)
You can read more on the concept of PropertyChanged here
You can invoke a property changed event from another class. Not particularly useful if you have all the sources. For closed source it might be. Though I consider it experimental and not production ready.
See this console copy paste example:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
public class Program
{
static void Main(string[] args)
{
var a = new A();
a.PropertyChanged += A_PropertyChanged;
var excpl = new Excpl();
excpl.Victim = a;
excpl.Ghost.Do();
}
private static void A_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine("Event triggered");
}
}
[StructLayout(LayoutKind.Explicit)]
public struct Excpl
{
[FieldOffset(0)]
public A Victim;
[FieldOffset(0)]
public C Ghost;
}
public class A : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
}
public class C : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void Do()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(""));
}
}
}

Why DataContext for inner object is not updated?

I have question about DataContext changes and I build example for understand this aspect.
I have MainUserControl on MainWindow. MainUserControl consists of number of User Controls.
One of such User Controls is SubUserControl1.
<Window x:Class="WpfApplicationUcBindingQuestion.MainWindow">
<Grid>
.....
<uc:MainUserControl />
</Grid>
</Window>
<UserControl x:Class="WpfApplicationUcBindingQuestion.MainUserControl">
<Grid>
.....
<uc:SubUserControl1 x:Name="subUserControl1" />
</Grid>
</UserControl>
And in MainWindow I have object of class Info. Class Info consists of a few inner classes.
One of them is, lets say, SubInfo. Both Info and SubInfo classes inherits from INotifyPropertyChanged.
And this is the code of them:
public class Info : INotifyPropertyChanged
{
private SubInfo m_subInfo = new SubInfo();
public Info()
{
}
public SubInfo SubInfo
{
get
{
return m_subInfo;
}
set
{
m_subInfo = value;
OnPropertyChanged("SubInfo");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public class SubInfo: INotifyPropertyChanged
{
private string m_subString = "subStr";
public SubInfo()
{
}
public string SubString
{
get
{
return m_subString;
}
set
{
m_subString = value;
OnPropertyChanged("SubString");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I want to set DataContext for MainUserControl to be object of class Info
and for SubUserControl1 DataContext will be Info.SubInfo.
The following code describes this:
<UserControl x:Class="WpfApplicationUcBindingQuestion.SubUserControl1">
<Grid>
.....
<TextBox Text="{Binding Path=SubString}"/>
</Grid>
</UserControl>
public MainUserControl()
{
InitializeComponent();
MainWindow mainWnd = (MainWindow)Application.Current.MainWindow;
Info info = mainWnd.Info;
this.DataContext = info;
this.subUserControl1.DataContext = info.SubInfo;
}
When new subInfo arrived I update inner object subInfo inside info object:
(This is function of MainWindow)
private void OnUpdateData()
{
SubInfo arrivedSubInfo = new SubInfo();
arrivedSubInfo.SubString = "newString";
m_info.SubInfo = arrivedSubInfo;
}
I want to see that DataContext for subUserControl1 is also changed.
But it doesn't happened and TextBox inside SubUserControl1 is not updated
and doesn't show "newString".
(Note: If I write inside OnUpdateData() function the following:
m_info.SubInfo.SubString = arrivedSubInfo.SubString;
(copy field-field and not whole object) it works,
but I dont 'want copy 50 field...)
Where I'm wrong?
Your help will be really appreciated.
Your problem is the following:
In your constructor, when you do that:
this.DataContext = info;
this.subUserControl1.DataContext = info.SubInfo;
You will set the DataContext ONLY once. Which means it will never change unless you write subUserControl1.DataContext = someNewDataContext somewhere.
What you can do to solve this :
The "proper solution":
Use a binding. In your XAML, just write:
<uc:SubUserControl1 x:Name="subUserControl1" DataContext="{Binding
SubInfo, UpdateSourceTrigger=PropertyChanged}" />
This will work, assuming that your SubInfo property fires the OnPropertyChanged event when it is set.
The "ugly solution":
Explicitly set your UserControl's DataContext in code-behind when you need it. Again, I wouldn't advise that and you are better off applying the first solution!

Concept of "UpdateSourceTrigger" Property, How to use it in WPF?

I have a TextBlock, binded with an Object and when i update property of object its not refleting on UI, Why ?
Code:
In Windows1.xaml
<TextBlock Name="txtName" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="100" Height="20" Margin="12,23,166,218" />
and In Windows.xaml.cs
public partial class Window1 : Window
{
Employee obj ;
public Window1()
{
InitializeComponent();
obj = new Employee();
obj.Name = "First";
txtName.DataContext = obj;
}
private void btnUpdate_Click(object sender, RoutedEventArgs e)
{
obj.Name = "changed";
}
}
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
set
{
this._name = value;
OnPropertyChanged(Name);
}
get { return this._name; }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
OnPropertyChanged(Name);
should be:
OnPropertyChanged("Name");
otherwise if the name is set to "Kent", you're raising a property changed event saying that the "Kent" property has changed, which obviously doesn't exist.
As for UpdateSourceTrigger, that only applies to the source. The property you've bound is the target, not the source. And it doesn't make sense for a TextBlock to update its source, because there's no way for the user to modify the TextBlock text. A TextBox, on the other hand, would make sense. In that case, UpdateSourceTrigger determines the point at which the text in the TextBox is pushed back to the source property (e.g. as the user types each character, or when they move away from the TextBox).
Pass the name of the property as string, instead of the property value, like so:
OnPropertyChanged("Name");
UpdateSourceTrigger is for binding with the source property i.e normal .net property so to it requires to set on options like property change with mode twoway for dynamic change ex.text of textbox being change and the which updtaes a label to change. Where as if you want the change event to fire at the end i.e lost focus or click use explicit option with updatesourcetrigger.

PropertyChanged doesn't work properly

I have a Silverlight application in which I implemented MVVM pattern.
In my application there is a child window on which I have ComboBox. I bound ItemsSource and SelectedItem of my combobox to a property (typeof ObservableCollection) and property of MyType appropriately. MyType is a "MODEL" derived from INotifyPropertyChanged. When my window is loaded I set values to this properties. But my combobox doesn't display selected item.
I found that when I set property which is bound to selected item (in ViewModel), the PropertyChanged event is null.
Can anyone help me. Thanks.
From the way you've described it the only thing being bound to is the ViewModel yet the only thing that implements INotifyPropertyChanged is MyType. Nothing is actually binding to the instance of my type to listen to its PropertyChanged event which is why its null.
It sounds like you haven't implemented INotifyPropertyChanged on your ViewModel.
PropertyChanged works fine, so it must be in your implementation of it. Simply implementing INotifyProperty changed isn't good enough, you have to explicity call the event.
For example, this will not work:
public class Model : INotifyPropertyChanged
{
public string Title { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
In order for it to work, you must raise the property changed. Easiest way is to encapsulate the logic in a method, like this:
public class Model : INotifyPropertyChanged
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
RaisePropertyChanged("Title");
}
}
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Of course you can put the event and the method in a base class to inherit from so multiple models can take advantage of it.

Update text in StatusBar in wpf using C#

I have a TextBox in StatusBar in wpf which I want to update.
I have a list of files in ListBox. On each file I would be doing some operation by calling say method ProcessFile(). So whenever the file processing is completed I want to show that file's name in the StatusBar text.
I have tried something like this:
private void button_Click(object sender, RoutedEventArgs e)
{
statusBar.Visibility = Visibility.Visible;
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(TimeConsumingMethod), frame);
Dispatcher.PushFrame(frame);
statusBar.Visibility = Visibility.Collapsed;
}
public object TimeConsumingMethod(Object arg)
{
((DispatcherFrame)arg).Continue = false;
foreach (string fileName in destinationFilesList.Items)
{
txtStatus.Text = fileName.ToString();
//Assume that each process takes some time to complete
System.Threading.Thread.Sleep(1000);
}
return null;
}
But I can only see the last file's name in the StatusBar. What's wrong with the code? How can I correct it?
There's more ways to do this.
Set content directly from code
You need give name to the TextBox so that you can access it's content:
XAML
<TextBox x:Name="myTextBox" />
C#
...
ProcessFile(someFileName);
myTextBox.Text = someFileName;
Use data binding
You need to create some object and set it as DataContext to the TextBox or some WPF element that contain that text box (status bar, window, ...).
XAML:
<TextBox Text="{Binding Path=ProcessedFileName}" />
C#
public MyClass : INotifyPropertyChanged
{
public string ProcessedFileName {get; set;}
public void ProcessFile(string someFileName)
{
// Processing file code here
// When done processing, set file name to property
ProcessedFileName = someFileName;
OnPropertyChanged("ProcessedFileName");
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
For more information on data binding see Data Binding Overview
When you are using a ViewModel, i would define a Property "ProcessedFile" in your ViewModel and bind the Textbox of your StatusBar to the Property.
Every time you processed a file i would set the Property "ProcessedFile" to the name of the file.
HereĀ“s some code for the ViewModel.
public class ViewModel : INotifyPropertyChanged {
private string _processedFile;
public string ProcessedFile {
get {
return _processedFile;
}
set {
if (_processedFile != value) {
_processedFile = value;
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs("ProcessedFile"));
}
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
public void ProcessFile() {
// Process the file
ProcessedFile = //Set the Property to the processed file
}
}
Heres the XAML to bind the TextBox to the Property. (I assume that the ViewModel is set as DataContext for the TextBox)
<TextBox Text="{Binding ProcessedFile, Mode=OneWay}"/>

Resources