I'm trying to bind a TextBlock using INotifyPropertyChanged event. But it is not updating anything to the TextBlock. The TextBlock is blank. My goal is to update the status of items which are displayed in different rows. I need to update the TextBlock's text and color based on the status.
Could anyone tell me what is wrong with my code?
public class ItemStatus : INotifyPropertyChanged
{
string itemStatus;
Brush itemStatusColor;
public string ItemStatus
{
get { return itemStatus; }
set
{
itemStatus = value;
this.OnPropertyChanged("ItemStatus");
}
}
public Brush ItemStatusColor
{
get { return itemStatusColor; }
set
{
itemStatusColor = value;
this.OnPropertyChanged("ItemStatusColor");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(
this, new PropertyChangedEventArgs(propName));
}
}
public class Items
{
List<ItemStatus> currentItemStatus;
public List<ItemStatus> CurrentItemStatus
{
get { return currentItemStatus; }
set { currentItemStatus = value; }
}
}
public partial class DisplayItemStatus : Page
{
....
....
public DisplayItemStatus()
{
foreach (Product product in lstProductList)
{
TextBlock tbItemStatus = new TextBlock();
....
Items objItems = new Items();
Binding bindingText = new Binding();
bindingText.Source = objItems;
bindingText.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
bindingText.Path = new PropertyPath(String.Format("ItemStatus"));
tbItemStatus.SetBinding(TextBlock.TextProperty, bindingText);
Binding bindingColor = new Binding();
bindingColor.Source = objItems;
bindingColor.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
bindingColor.Path = new PropertyPath(String.Format("ItemStatusColor"));
tbItemStatus.SetBinding(TextBlock.ForegroundProperty, bindingColor);
grdItemsList.Children.Add(tbItemStatus);
}
}
private void UpdateItems_Click(object sender, MouseButtonEventArgs e)
{
int intCount = 0;
List<Product> ProductList = new List<Product>();
List<ItemStatus> ItemList = new List<ItemStatus>();
ProductList = GetProducts();
foreach (Product product in ProductList)
{
intCount++;
UpdateStatus(intCount, ItemList);
}
}
public void UpdateStatus(int intIndex, List<ItemStatus> ItemList)
{
ItemStatus status = new ItemStatus();
status.ItemStatus = strOperationStatus;
status.ItemStatusColor = brshForegroundColor;
ItemList.Add(status);
}
}
Well, the specific problem here is that you're binding the TextBlock to an Item and not the ItemStatus. But you're also doing things the hard way, you really should do the binding details in XAML. Expose a collection of ItemStatus's from your view model, and have a ListBox or something with its ItemsSource bound to the collection. Then you'll need a DataTemplate which defines the TextBlock and the bindings to the ItemStatus.
Here's a good walkthrough for it in general
Related
I am trying to make a really simple app to learn DataBinding and events. The following code is supposed to change the label content when i click on a button, but actually it changes the property but doesn't update the label.
This is the main code :
public MainWindow()
{
InitializeComponent();
environments = new ObservableCollection<Env>();
environments.Add(new Env("env1", new ObservableCollection<Cell>()));
environments.Add(new Env("env2", new ObservableCollection<Cell>()));
foreach (Env e in environments)
{
Label label = new Label
{
Content = e.Name
};
pnlMain.Children.Add(label);
}
}
private void ChangeEnvName_Click(object sender, RoutedEventArgs e)
{
foreach (Env env in environments)
{
env.Name = "test";
}
}
And this is the Env class :
class Env : INotifyPropertyChanged
{
//membres
#region membres
private string _name;
private ObservableCollection<Cell> _cells;
#endregion
//propriétés
#region propriétés
public string Name
{
get { return this._name; }
set
{
if (this._name != value)
{
this._name = value;
this.NotifyPropertyChanged("Name");
}
}
}
public ObservableCollection<Cell> Cells
{
get { return this._cells; }
set
{
if (this._cells != value)
{
this._cells = value;
this.NotifyPropertyChanged("Cells");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
//méthodes
#region méthodes
public void NotifyPropertyChanged(string propName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
#endregion
//constructeur
#region contructeur
public Env(string name, ObservableCollection<Cell> cells)
{
_name = name;
_cells = cells;
}
#endregion
}
What's the problem? Isn't it suppose the update the label.content when i update Env.Name ?
You haven't bound the Content property of the Label to the Name property. You have just set it to a string. Try this:
foreach (Env e in environments)
{
Label label = new Label();
label.SetBinding(Label.ContentProperty, new Binding("Name") { Source = e });
pnlMain.Children.Add(label);
}
Or create an Environments property that returns environments, set the DataContext to this and bind to Environments[index].Name. If you don specify an explicit Source of the binding, it will look for the property in its current DataContext which may be inherited from a parent element. Please see the docs for more information.
I'm new to WPF and I'm having some trouble with my existing setup to get the list box selected item to appear in the text box.
The picture here represents the issue. I typed "12 HOUR" in the text box, which then filters the listbox to those items with "12 HOUR" anywhere in the string. But when I click "12 Hour Nasal" in the list box, I now want to reflect that choice back in the text box:
http://i.imgur.com/ZCYAolT.png
Here is my XAML for the user control containing the listbox and textbox:
<UserControl x:Class="SCM_AllergyRecModule.SearchAndSelectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d">
<StackPanel Width="300">
<TextBox x:Name="Filter" Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}"/>
<ListBox Width ="300" Height="50" x:Name="ListBoxControl"
ItemsSource="{Binding Path=Allergens}"
SelectedItem="{Binding Path=SelectedAllergen}">
</ListBox>
</StackPanel>
And here is the ViewModel:
namespace SCM_AllergyRecModule
{
public class SearchAndSelectViewModel
{
private ICollectionView allergens;
private string selectedAllergen;
private string filter = "";
public string Filter
{
get
{
return this.filter.ToUpperInvariant();
}
set
{
if (this.filter != value)
{
this.filter = value;
this.Allergens.Refresh();
}
}
}
private bool ContainsFilter(object item)
{
var product = item as string;
if (product == null)
{
return false;
}
if (string.IsNullOrEmpty(this.Filter))
{
return true;
}
if (product.ToUpperInvariant().Contains(this.Filter))
{
return true;
}
return false;
}
public SearchAndSelectViewModel()
{
var cvs = new CollectionViewSource();
cvs.Source = MainWindow.scmAllergens;
this.allergens = cvs.View;
this.allergens.Filter = ContainsFilter;
}
public ICollectionView Allergens
{
get
{
return this.allergens;
}
}
public string SelectedAllergen
{
get
{
return this.selectedAllergen;
}
set
{
if (this.selectedAllergen != value)
{
this.selectedAllergen = value;
}
}
}
}
}
Update 1
I added the INotifyPropertyChanged interface to my class and have it being raised on SelectedAllergen in the setter. I added an event handler called SearchAndSelectViewModel_PropertyChanged to handle the SelectedAllergen property changing and set it in the constructor.
Now when I click an item in the listbox, I do see it setting the Filter to the SelectedItem and the list filters to that item so nothing else shows. But still, the text box text is not changing? See screenshot below. This is after I typed in "PEAN" in the textbox, then the listbox filtered to two choices, and I chose "PEANUTS (FOOD)", which then refiltered the list box to just show that choice but didn't set the text box to "PEANUTS (FOOD)":
http://imgur.com/dNxuVI5
Updated ViewModel
public class SearchAndSelectViewModel : INotifyPropertyChanged
{
private ICollectionView allergens;
private string selectedAllergen;
private string filter;
public string Filter
{
get
{
return this.filter.ToUpperInvariant();
}
set
{
if (this.filter != value)
{
this.filter = value;
this.Allergens.Refresh();
}
}
}
private bool ContainsFilter(object item)
{
var product = item as string;
if (product == null)
{
return false;
}
if (string.IsNullOrEmpty(this.Filter))
{
return true;
}
if (product.ToUpperInvariant().Contains(this.Filter))
{
return true;
}
return false;
}
private void SearchAndSelectViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "SelectedAllergen":
this.Filter = this.SelectedAllergen;
break;
}
}
public SearchAndSelectViewModel()
{
filter = "";
var cvs = new CollectionViewSource();
cvs.Source = MainWindow.scmAllergens;
this.allergens = cvs.View;
this.allergens.Filter = ContainsFilter;
this.PropertyChanged += SearchAndSelectViewModel_PropertyChanged;
}
public ICollectionView Allergens
{
get
{
return this.allergens;
}
}
public string SelectedAllergen
{
get
{
return this.selectedAllergen;
}
set
{
if (this.selectedAllergen != value && value != null)
{
this.selectedAllergen = value;
OnPropertyChanged("SelectedAllergen");
}
}
}
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You need to implement the INotifyPropertyChanged interface and you can raise it in your property setter. Since you are also binding your TextBox to the Filter property you need to set the Filter property when your SelectedAllergen changes.
INotifyPropertyChanged example:
public class MyViewModel : INotifyPropertyChanged
{
//...
private int myProperty = 0;
public int MyProperty
{
get { return myProperty; }
set
{
myProperty = value;
// Raise the property changed notification
OnPropertyChanged("MyProperty");
}
}
// INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Just getting started with data binding in C# and looking for some help. The below binding statements break (Visible property stops toggling with MyBool & MyBoolInverse) when the line binding SelectedItem of the combo box to MyEnumVar of the BusinessObject executes. Binding directly to the object instead of the BindingSource, or binding to SelectedValue instead of SelectedItem, has the same effect. Further, the value of MyEnumVar doesn't change with selections to the combo box. What am I doing wrong?
public partial class Form1 : Form
{
BindingSource bs = new BindingSource();
private BusinessObject bo = new BusinessObject();
public Form1()
{
InitializeComponent();
bs.DataSource = bo;
// Checkbox determines what type of dialog to display.
boolCheckBox.DataBindings.Add("Checked", bs, "MyBool", true,
DataSourceUpdateMode.OnPropertyChanged);
trueBox.DataBindings.Add("Visible", bs, "MyBoolInverse");
falseComboBox.DataBindings.Add("Visible", bs, "MyBool");
falseBox.DataBindings.Add("Visible", bs, "MyBool");
falseButton.DataBindings.Add("Visible", bs, "MyBool");
myEnumComboBox.DataSource = Enum.GetValues(
typeof(BusinessObject.MyEnum));
// Line below breaks above bindings, same for SelectedValue.
myEnumComboBox.DataBindings.Add("SelectedItem", bs, "MyEnumVar");
}
}
class BusinessObject : INotifyPropertyChanged
{
public enum MyEnum { RED, BLU }
MyEnum _MyEnumVar;
public MyEnum MyEnumVar
{
get { return _MyEnumVar; }
set
{
if (value != _MyEnumVar)
{
_MyEnumVar = value;
NotifyPropertyChanged("MyEnumVar");
}
}
}
private bool _MyBool;
public bool MyBool
{
get { return _MyBool; }
set
{
if (value != _MyBool)
{
_MyBool = value;
MyBoolInverse = !value;
NotifyPropertyChanged("MyBool");
}
}
}
private bool _MyBoolInverse;
public bool MyBoolInverse
{
get { return _MyBoolInverse; }
private set
{
if (value != _MyBoolInverse)
{
_MyBoolInverse = value;
NotifyPropertyChanged("MyBoolInverse");
}
}
}
public BusinessObject()
{
MyBoolInverse = !MyBool;
MyEnumVar = MyEnum.BLU;
}
// Boilerplate INotifyPropertyChanged implementation & helper.
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Visible property has problems with binding. Try manual 'binding'. Something along the lines of
trueBox.Visible = bo.MyBoolInverse;
bo.PropertyChanged += (s, e) => {
if(e.PropertyName == "MyBoolInverse")
trueBox.Visible = bo.MyBoolInverse;
};
Edit: Also, binding to MyEnumVar is not working beacause it is not declared as a public property.
If I had an Observable collection like so :
public ObservableCollection<SpecialPriceRow> SpecialPriceRows = new ObservableCollection<SpecialPriceRow>();
SpecialPriceRow class :
public class SpecialPriceRow : INotifyPropertyChanged
{
public enum ChangeStatus
{
Original,
Added,
ToDelete,
Edited
}
public ChangeStatus Status { get; set; }
public string PartNo { get; set; }
private decimal _price;
public decimal Price
{
get
{
return _price;
}
set
{
if (value != _price)
{
_price = value;
Status = ChangeStatus.Edited;
OnPropertyChanged("Status");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Would it be possible for me to bind a Label in the XAML to the count of objects that are say ... Added? So I could get something like this :
Where green is the count of "Added" objects within the collection. How would I go about doing something like this?
I've written up a ViewModel which will perform the desired functionality you are looking for.
class VM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<SpecialPriceRow> _SpecialPriceRows = new ObservableCollection<SpecialPriceRow>();
private int _Original = 0;
private int _Added = 0;
private int _ToDelete = 0;
private int _Edited = 0;
public VM()
{
PropertyChanged = new PropertyChangedEventHandler(VM_PropertyChanged);
//The following lines in the constructor just initialize the SpecialPriceRows.
//The important thing to take away from this is setting the PropertyChangedEventHandler to point to the UpdateStatuses() function.
for (int i = 0; i < 12; i++)
{
SpecialPriceRow s = new SpecialPriceRow();
s.PropertyChanged += new PropertyChangedEventHandler(SpecialPriceRow_PropertyChanged);
SpecialPriceRows.Add(s);
}
for (int j = 0; j < 12; j+=2)
SpecialPriceRows[j].Price = 20;
}
private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
private void SpecialPriceRow_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Status")
UpdateStatuses();
}
public ObservableCollection<SpecialPriceRow> SpecialPriceRows
{
get
{
return _SpecialPriceRows;
}
}
private void UpdateStatuses()
{
int original = 0, added = 0, todelete = 0, edited = 0;
foreach (SpecialPriceRow SPR in SpecialPriceRows)
{
switch (SPR.Status)
{
case SpecialPriceRow.ChangeStatus.Original:
original++;
break;
case SpecialPriceRow.ChangeStatus.Added:
added++;
break;
case SpecialPriceRow.ChangeStatus.ToDelete:
todelete++;
break;
case SpecialPriceRow.ChangeStatus.Edited:
edited++;
break;
default:
break;
}
}
Original = original;
Added = added;
ToDelete = todelete;
Edited = edited;
}
public int Original
{
get
{
return _Original;
}
set
{
_Original = value;
PropertyChanged(this, new PropertyChangedEventArgs("Original"));
}
}
public int Added
{
get
{
return _Added;
}
set
{
_Added = value;
PropertyChanged(this, new PropertyChangedEventArgs("Added"));
}
}
public int ToDelete
{
get
{
return _ToDelete;
}
set
{
_ToDelete = value;
PropertyChanged(this, new PropertyChangedEventArgs("ToDelete"));
}
}
public int Edited
{
get
{
return _Edited;
}
set
{
_Edited = value;
PropertyChanged(this, new PropertyChangedEventArgs("Edited"));
}
}
}
Take note of the comments in the constructor. You need to point the PropertyChanged event of each SpecialPriceRow to the UpdateStatuses function in order for this to work properly.
Now all you need to do is bind your labels to the appropriate properties in the ViewModel.
If your SpecialPriceRows list becomes very large, you may want to consider calculating the status counts a bit differently. Currently, it is iterating through the entire list every time one instance is updated. For this to perform better, you may want to keep the old value of the status in the SpecialPriceRow class and every time an update occurs, increment the new status count and decrement the old one.
I'm not aware of any builtin functionality to do this. I would create a custom property in your data context class that does the counting and bind to this.
Something like this:
public int AddedCount
{
get
{
return SpecialPriceRows.Where(r => r.Status == ChangeStatus.Added).Count();
}
}
Then whenever an item is changed or added you need to explicitly raise the property changed for this:
public void AddItem()
{
...
OnPropertyChanged("AddedCount");
}
Then you only need to bind in your XAML code like:
<TextBlock Text="{Binding AddedCount}" />
You may need to subscribe to the change events in your collection to know when an item changes.
Alternative:
You can also create a ListCollectionView with a specific filter and bind to its Count property:
AddedItems = new ListCollectionView(TestItems);
AddedItems.Filter = r => ((SpecialPriceRow)r).Status == ChangeStatus.Added;
In your XAML you would then bind to the Count property of this:
<TextBlock Text="{Binding AddedItems.Count}" />
This has the advantage that it will automatically keep track of added and removed items in the collection and update itself. You have to refresh it manually though when the property of an item changes which affects the filter.
I have an ObservableCollection of ChildViewModels with somewhat complex behaviour.
When I go to edit a row - the DataGrid goes into 'edit-mode' - this effectively disables UI-notifications outside the current cell until the row is committed - is this intended behaviour and more importantly can it be changed?
Example:
public class ViewModel
{
public ViewModel()
{
Childs = new ObservableCollection<ChildViewModel> {new ChildViewModel()};
}
public ObservableCollection<ChildViewModel> Childs { get; private set; }
}
public class ChildViewModel : INotifyPropertyChanged
{
private string _firstProperty;
public string FirstProperty
{
get { return _firstProperty; }
set
{
_firstProperty = value;
_secondProperty = value;
OnPropetyChanged("FirstProperty");
OnPropetyChanged("SecondProperty");
}
}
private string _secondProperty;
public string SecondProperty
{
get { return _secondProperty; }
set
{
_secondProperty = value;
OnPropetyChanged("SecondProperty");
}
}
private void OnPropetyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
And in View:
<Window.Resources>
<local:ViewModel x:Key="Data"/>
</Window.Resources>
<DataGrid DataContext="{Binding Source={StaticResource Data}}" ItemsSource="{Binding Childs}"/>
Notice how the second notification when editing first column is hidden until you leave the row.
EDIT: Implementing IEditableObject does nothing:
public class ChildViewModel : INotifyPropertyChanged,IEditableObject
{
...
private ChildViewModel _localCopy;
public void BeginEdit()
{
_localCopy = new ChildViewModel {FirstProperty = FirstProperty, SecondProperty = SecondProperty};
}
public void EndEdit()
{
_localCopy = null;
}
public void CancelEdit()
{
SecondProperty = _localCopy.SecondProperty;
FirstProperty = _localCopy.FirstProperty;
}
}
This behavior is implemented in DataGrid using BindingGroup. The DataGrid sets ItemsControl.ItemBindingGroup in order to apply a BindingGroup to every row. It initializes this in MeasureOverride, so you can override MeasureOverride and clear them out:
public class NoBindingGroupGrid
: DataGrid
{
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = base.MeasureOverride(availableSize);
ClearBindingGroup();
return desiredSize;
}
private void ClearBindingGroup()
{
// Clear ItemBindingGroup so it isn't applied to new rows
ItemBindingGroup = null;
// Clear BindingGroup on already created rows
foreach (var item in Items)
{
var row = ItemContainerGenerator.ContainerFromItem(item) as FrameworkElement;
row.BindingGroup = null;
}
}
}
This is very old question, but a much better solution which doesn't require subclassing DataGrid exists. Just call CommitEdit() in the CellEditEnding event:
bool manualCommit = false;
private void MyDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (!manualCommit)
{
manualCommit = true;
MyDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
manualCommit = false;
}
}
ok, so, here is the problem. Observable Collection does NOT notify of objects that it contains changing. It only notifies on add/remove/etc. operations that update the collection is-self.
I had this problem and had to manually add my columns to the datagrid, then set the Binding item on the Column object. so that it would bind to my contents.
Also, I made the objects that are in my ICollectionView derive from IEditableObject so when they are "updated" the grid will refresh itself.
this sucks, but its what i had to do to get it to work.
Optionally, you could make your own ObservableCollection that attaches/detaches property changed handlers when an item is addeed and remove.