I am doing some changes in my WPF project to make it less deprecated.
One of the things I am trying to do is Binding my Textbox.Text value to a simple Class as shown below.
<TextBox x:Name="txtNCM"
Grid.Column="1"
Margin="5"
MaxLength="8"
Text="{Binding Path=Name}"
</TextBox>
public partial class wCad_NCM : UserControl, INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged("Name");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public wCad_NCM()
{
InitializeComponent();
}
}
Everytime I use the Immediate Window to display the Name's value, it is shown as null. I am really new to this, so I had to search for a similar situation to adapt, but I don't know how to make this work :(
You need to set the DataContext and give Name a value.
To do that, change your constructor to include this:
public wCad_NCM()
{
InitializeComponent();
DataContext = this; // Sets the DataContext
Name = "Test";
}
This should make it work, but is typically bad practice. See http://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html for more details.
Additionally, I tried running this and ran into a name hiding problem. Try using a variable name other than Name as FrameworkElement already contains it.
Related
I am using MVVM in a WPF application with C# and got a problem binding a ComboBox correctly.
This is my ComboBox line in the XAML:
<ComboBox ItemsSource="{Binding Repository.Models}" SelectedValue="{Binding Repository.SelectedModel}" DisplayMemberPath="Name"></ComboBox>
This is the interesting part of my Repository:
class Repository : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<Model> _models;
public ObservableCollection<Model> Models
{
get
{
return _models;
}
set
{
_models = value;
NotifyPropertyChanged("Models");
}
}
private Model _selectedModel;
public Model SelectedModel
{
get
{
return _selectedModel;
}
set
{
_selectedModel = value;
NotifyPropertyChanged("SelectedModel");
}
}
This is the interesting part of my Model class:
abstract class Model : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
So when I select/change different items of the combobox a DataGrid that is binded to Repository.SelectedModel.Parameters does update just as i want it to.
Because of that I know, that the binding does work!
When I restart the application and debug into my Repository, I see that there is a SelectedModel (deserialised on startup) but the ComboBox stays blank. The DataGrid though does show the right data.
So the binding itself does work, but the binding to the ComboBoxLabel somehow fails.
I tried a lot of things like switching between SelectedItem and SelectedValue, between Binding and Binding Path, between IsSynchronizedWithCurrentItem true and false, but nothing worked so far.
Do you see my mistake?
Thanks in advance!
EDIT
Here is the interesting part of my MainWindowViewModel:
class MainWindowViewModel : INotifyPropertyChanged
{
//init MVVM pattern
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private Repository _repository;
public Repository Repository
{
get
{
return _repository;
}
set
{
_repository = value;
NotifyPropertyChanged("Repository");
}
}
And here is my App.xaml.cs where I init my DataContext:
//init point of app
public partial class App : Application
{
private MainWindowViewModel mainWindowViewModel;
//gets fired as the app starts
protected override void OnStartup(StartupEventArgs e)
{
//create the ViewModel
mainWindowViewModel = new MainWindowViewModel();
//create the mainWindow
var mainWindow = new MainWindow();
mainWindow.DataContext = mainWindowViewModel;
//show the mainWindow
mainWindow.Show();
}
When I restart the application and debug into my Repository, I see that there is a SelectedModel (deserialised on startup) but the ComboBox stays blank. The DataGrid though does show the right data.
Looks like the deserialization is the problem.
You have a selected item which was deserialized. That means that a new Model instance was created which has a Name of whatever, and Properties that are whatever. And you have a list of Model instances in an ObservableCollection<Model> which are displayed in a ComboBox.
And you assure us that at least sometimes, you have ComboBox.SelectedItem bound to SelectedModel, though for some reason the code in your question binds ComboBox.SelectedValue instead. That's not going to work. Here's how ComboBox.SelectedValue would be used:
<ComboBox
ItemsSource="{Binding Repository.Models}"
SelectedValuePath="Name"
SelectedValue="{Binding SelectedModelName}"
/>
...and you would have to have a String SelectedModelName { get; set; } property on your viewmodel. The Name property of the selected Model would be assigned to that by the ComboBox when the selection changed. But you don't have SelectedModelName, and you don't want it, so forget about SelectedValue.
Back to SelectedItem. The ComboBox gets the value of SelectedModel from the binding, and tries to find that exact object in its list of Items. Since that exact object is not in that list, it selects nothing. There is probably an item in Repository.Models that has the same name and has identical Properties, but it is not the same actual instance of the Model class. ComboBox doesn't look for an identical twin of the value in SelectedItem; it looks for the same object.
SelectedModel.Properties works in the DataGrid because the DataGrid doesn't know or care what's in Models. You give it a collection, it's good.
So: If you want to deserialize a SelectedModel and have it mean anything, what you need to do is go ahead and deserialize, but then find the equivalent item in Repository.Models (same Name, same Properties), and assign that actual object instance to SelectedModel.
You may be tempted to overload Model.Equals(). Don't. I've done that to solve the same problem. The resulting behavior is not expected in C# and will bite you, hard, and when you least expect it, because you are invisibly altering behavior that happens in framework code. I've spent days tracking down bugs I created that way, and I'll never do it to myself again.
Try SelectedItem instead of SelectedValue in ComboBox.
I have a some XAML as follows (a simple Label and Button):
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Test="clr-namespace:WpfApplication2">
<StackPanel DataContext="{Binding Path=TestPerson}">
<Label Content="{Binding Path=Name}"></Label>
<Button Content="Button" Click="button1_Click" />
</StackPanel>
</Window>
in the code behind I have:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private Person _person = new Person();
public Person TestPerson { get { return _person; } }
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
_person.Name = "Bill";
//_person = new Person() { Name = "Bill" };
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TestPerson"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
and the class Person is:
public class Person
{
string _name = "Bob";
public string Name
{
get { return _name; }
set { _name = value; }
}
}
As it is, firing the Propertychanged event does not cause the Label's contents to change to Bill.
I've found I am able to overcome this by either:
Assigning a new object to _person (as in the commented out line)
Removing the DataContext from the StackPanel and have Label bind to Path=TestPerson.Name
I don't understand why I have to actually assign a NEW object to _person for the Label to update, or use the FULL path in the binding.
Is there a way to update the Label without supplying the full path (relying on the DataContext), and without assigning a new object to _person?
You raise PropertyChanged for the Person instance TestPerson. However, TestPerson hasn't changed, it is the Name property of TestPerson that has changed and that is the property the Label is binding to.
Edit: To answer why your first two versions work
Assigning a new object to _person (as in the commented out line)
Here you are actually changing the value of TestPerson and because DataContext is inherited by the children, the Label gets a new DataContext as well so that's why the Binding is updated.
Removing the DataContext from the StackPanel and have Label bind to
Path=TestPerson.Name
This is something I've never seen. The same binding subscribes to PropertyChanged for both TestPerson and Name in Person so raising PropertyChanged for any of these properties will work.
If you want to overcome this without implementing INotifyPropertyChanged for Person, you can change set UpdateSourceTrigger to Explicit
<Label Name="label"
Content="{Binding Path=Name, UpdateSourceTrigger=Explicit}"/>
And update the Binding manually whenever Name changes
private void button1_Click(object sender, RoutedEventArgs e)
{
_person.Name = "Bill";
BindingExpression be = label.GetBindingExpression(Label.ContentProperty);
be.UpdateTarget();
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("TestPerson"));
}
}
Otherwise, just implement INotifyPropertyChanged for Person as well and it will work
public class Person : INotifyPropertyChanged
{
string _name = "Bob";
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You need a little change in your XAML...
In your code behind, instead of setting DataContext as this, set it in XAML via Binding...
<StackPanel DataContext="{Binding RelativeSource={RelativeSource
AncestorType= {x:Type Window},
Mode=FindAncestor},
Path=TestPerson}">
<Label Content="{Binding Path=Name}"></Label>
<Button Content="Button" Click="button1_Click" />
</StackPanel>
Remove the
DataContext = this;
from your code behind.
Let me know if this helps.
public class myClass : INotifyPropertyChanged
{
public string myName(string myNameIs)
{
Name = myNameIs;
return myNameIs;
}
public string My = "Hasan";
public string Name {
get { return My; }
set
{
My = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// Raise the PropertyChanged event
this.PropertyChanged( this, new PropertyChangedEventArgs(
propertyName));
}
}
}
.
XAML:
<TextBlock Height="42" Margin="107,245,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="159" DataContext="{Binding Source={StaticResource myClassDataSource}}"/>
This is working. But when i update property then it isn`t work?
Your code is rather confusing, you seem to be all over the place with it. I know this isn't the question you asked, but i thought i would point this out anyway:
your member variable is declared as public (public string My = "Hasan";)
your member variable has a totally different name to its property (My and Name)
you have a setter for the public property, and also a setting function (myName(string myNameIs))
you are returning the same value from the setting function as what you passed in
Here is an example of how you could rewrite it:
public class MyClass : INotifyPropertyChanged
{
//normal default constructor
public MyClass()
{
_name = "Hasan";
}
//extra constructor for when you need to set the name to something other than the default
//although this is really only useful if you have no setter on the Name property
public MyClass(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// Raise the PropertyChanged event
this.PropertyChanged(this, new PropertyChangedEventArgs(
propertyName));
}
}
private string _name;
}
You just need to set the TextBlock (or it's parent's) DataContext property to an instance of this class.
Next bind the Text property to the backing property like this
<TextBlock Text="{Binding Name}"/>
Try going through a few tutorials online (or a book) instead of trying to forge your way through. It's easy once you get how DataBinding works.
Update: Once I formatted your question correctly, I could see the XAML you are using...
The mistake here is that you're trying to use the ElementName property (which is used to bind one UI element with another by name). This isn't what you're trying to achieve.
I have a binding in my view as follows
<TextBox Grid.Row="3" Grid.Column="1" DataContext="{Binding FileStore}" Text="{Binding Path=StoreId}" Foreground="Black"/>
FileStore.StoreId is a string. In my code I changed the StoreId at some point
FileStore.StoreId = "1234";
But the view is not updating the TextBox content. I could think of one possible reason-as string is immutable the assignment allocates a new string.So, the Textbox is still binding to the old instance. Do you agree? How can I tackle the situation?
Your FileStore class should implement INotifyPropertyChanged, so that the binding engine is notified when the value of a property is changed
class FileStore : INotifyPropertyChanged
{
private string _storeId;
public string StoreId
{
get { return _storeId; }
set
{
_storeId = value;
OnPropertyChanged("StoreId");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
You should realize that FileStore is not changing (it's the same object), you can try by declaring a new FileStore with the new StoreId and then replace the current FileStore.
NewFileStore = new FileStoreType();
NewFileStore.StoreId="1234";
this.FileStore = NewFileStore;
Anyway, your FileStore class should be in a ViewModel which implements INotifyPropertyChanged.
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.