PropertyChanged Fody accesses ObservableCollection - c#

Is it possible to instruct Fody to generate PropertyChanged Events for the Properties Color1
and Color2 if the corresponding Items in the ObservableCollection _colors are changing?
public class MyModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Name { get; set; }
public Brush Color1 => _colors[0];
public Brush Color2 => _colors[1];
private ObservableCollection<Brush> _colors;
public MyModel()
{
_colors = new ObservableCollection<Brush>()
{
Brushes.Transparent,
Brushes.Black,
};
}
public void DoSomething()
{
_colors[0] = Brushes.Green;
_colors[1] = Brushes.Red;
}
protected void OnPropertyChanged(PropertyChangedEventArgs eventArgs)
{
PropertyChanged?.Invoke(this, eventArgs);
}
}
For the Name Property the Event will be generated, but not for Color1 and Color2 (see extract from ILSpy):
public string Name
{
[CompilerGenerated]
get
{
return <Name>k__BackingField;
}
[CompilerGenerated]
set
{
if (!string.Equals(<Name>k__BackingField, value, StringComparison.Ordinal))
{
<Name>k__BackingField = value;
OnPropertyChanged(<>PropertyChangedEventArgs.Name);
}
}
}
public Brush Color1 => _colors[0];
public Brush Color2 => _colors[1];

Currently Color1 and Color2 are read-only properties, so there is no need generate PropertyChanged events for them. What you want is code to fire the event for property A when field b is set. I doubt that any code generator will do that (fields don't have setters, where the event needs to be invoked).
The Fody docs state that
All classes that implement INotifyPropertyChanged will have notification code injected into property setters.
So, maybe your best try is to create properties with private setters (and remove your fields _color1&2).

Related

PropertyChangedCallback not triggered when DependencyObject Class Member is Modified

I created a DependencyObject with properties in it, I also have it inherit INotifyPropertyChanged.
But when it is implemented as a DependencyProperty, it does not trigger PropertyChangedCallback when I change a single property from the DependencyObject both in Design and Code.
This is the Dependency Object that I will use for my CustomControl.
public class Basemap : DependencyObject, INotifyPropertyChanged
{
private string identifier;
private string name;
private string alias;
private string url;
private Map.DetailRange detailrange;
private Map.Attribution attribution;
public string Identifier
{
get => identifier;
set
{
identifier = value;
OnPropertyChanged("Identifier");
}
}
public string Name
{
get => name;
set
{
name = value;
OnPropertyChanged("Name");
}
}
public string Alias
{
get => alias;
set
{
alias = value;
OnPropertyChanged("Alias");
}
}
public string URL
{
get => url;
set
{
url = value;
OnPropertyChanged("URL");
}
}
public Map.DetailRange DetailRange
{
get => detailrange;
set
{
detailrange = value;
OnPropertyChanged("DetailRange");
}
}
public Map.Attribution Attribution
{
get => attribution;
set
{
attribution = value;
OnPropertyChanged("Attribution");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
It has a PropertyChangedEventHandler and Invoking it whenever the OnPropertyChanged is called, just like in this GUIDE
This it the DependecyProperty I implimented into the CustomControl that has a PropertyChangedCallback.
public static DependencyProperty BasemapProperty = DependencyProperty.Register("Basemap", typeof(Basemap), typeof(Browser), new PropertyMetadata(null, BasemapChanged));
private static void BasemapChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("Basemap Changed");
}
But the PropertyChangedCallback is not triggered when an individual property's value is changed, but it is triggered only when the whole DependecyObject is updated or inserted. Both in Design and Code
<Window.Resources>
<mMAP:Basemap x:Key="OpenStreetMap"
Identifier="OpenStreetMap.Standard"
Name="OpenStreetMap Standard"
Alias="OpenStreetMap"
URL="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
DetailRange="0,0,18"
Attribution="© OpenStreetMap contributors, CC-BY-SA" />
</Window.Resources>
Can anyone suggest any fixes to this?
Thank you.
Edit:
I assignend the PropertyChanged event from the DependecyObject to the control. Basemap.PropertyChanged += Basemap_PropertyChanged; so it can be triggered every time any member of the DependecyObject class. It may be sacrilegious to do it to WPF, but works for me.
PS:
I needed it to be grouped, for it is a configuration for the CustomControl.
You are not binding to the Dependency Property you defined in the control, that is why the PropertyChangedCallback BasemapChanged is not triggered.
While it works on some cases, I try to avoid implementing the INotifyPropertyChanged Interface on Controls and use only Dependency Properties instead when binding is required.
public static DependencyProperty AliasProperty = DependencyProperty.Register(
nameof(Alias),
typeof(string),
typeof(Basemap),
new PropertyMetadata(null, AliasPropertyChangedCallback));
public string Alias
{
get { return (string)GetValue(Alias); }
set { SetValue(Alias, value); }
}
private static void AliasPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine($"New Value of Alias: {e.NewValue}");
}
See: Dependency properties overview (WPF .NET)

How do I bind FontSize for WPF TextBox in XAML to a class member variable?

How do I bind FontSize for WPF TextBox in XAML to a class member variable?
I have a collection of fonts that I use through the application.
I would like to change the values of those fonts dynamically in my code behind and then have the changes reflected during runtime.
How do I achieve this?
Here is what my class definition looks like
public ClassFoo
{
public double FontSize {get; set;}
}
This is how I define my class in MainWindow.xaml.cs:
public ClassFoo SampleClass;
Here is my what my XAML looks like:
<TextBlock Name="txtSample" Text="SomeText"
FontSize="{Binding SampleClass.FontSize}"/>
Then at runtime, I instantiate the class and initialize it:
SampleClass = new ClassFoo()
{
FontSize = 16;
}
I would create it like that:
public class MainWindow : Page
{
public Foo Foo { get; set; }
public MainWindow()
{
DataContext = this;
}
}
public class Foo : INotifyPropertyChanged
{
private double _fontSize;
public double FontSize
{
get { return _fontSize; }
set
{
_fontSize = value;
OnPropertyChanged(nameof(FontSize));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and then call it like:
<TextBlock Name="txtSample" Text="SomeText"
FontSize="{Binding Foo.FontSize}"/>
Most likely you need a DataContext = this; in your constructor for Mainwindow.xaml.cs. You also need in Mainwindow.xaml.cs that returns SampleClass.
You can only bind to public properties so the first thing to do would be to make SampleClass a property:
public ClassFoo SampleClass { get; set; }
And if you intend to set it dynamically at runtime after the constructor of the window has returned, the window should implement the INotifyPropertyChanged interface and raise change notfications for the taget property to get automatically updated.
Finally the source of the binding must be set to the window somehow. You could set the Source property of the binding explicitly or set the DataContext of the TextBlock or any of its parent element to an instance of the window.
Try this implementation of the MainWindow class together with the XAML markup you posted:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
this.Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
SampleClass = new ClassFoo()
{
FontSize = 16
};
}
private ClassFoo _sampleClass;
public ClassFoo SampleClass
{
get { return _sampleClass; }
set { _sampleClass = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Data Binding issue using NotificationBase

Custom_View.xaml
<UserControl>
<local:Custom_Text_Field
Custom_Text_Field_Color="{x:Bind ViewModel.Color1 , Mode=TwoWay}">
</local:Custom_Text_Field>
<local:Custom_Text_Field
Custom_Text_Field_Color="{x:Bind ViewModel.Color2 , Mode=TwoWay}">
</local:Custom_Text_Field>
<Button Click="{x:Bind ViewModel.ChangeColor"/>
</UserControl>
Custom_View.cs
public sealed partial class Custom_View : UserControl
{
public Custom_View_VM ViewModel { get; set; }
public Custom_View()
{
ViewModel = new Custom_View_VM();
this.InitializeComponent();
}
}
Custom_View_VM.cs
public class Custom_View_VM : NotificationBase
{
public Brush Color1 { get; set; }
public Brush Color2 { get; set; }
public void ChangeColor{//change color1 or color2};
}
I used the NotificationBase class from this example: https://blogs.msdn.microsoft.com/johnshews_blog/2015/09/09/a-minimal-mvvm-uwp-app/
If I affect values for Color1 or Color2 in the constructeur, it work (change the view), but after a call to ChangeColor, values in the View model are changed but it didn't impact the view.
For the UI to update it should receive a PropertyChanged event. You should use NotificationBase's mechanism to set properties which will also raise the PropertyChanged event:
public class Custom_View_VM : NotificationBase
{
private Brush color1;
public Brush Color1
{
get { return color1; }
set { SetProperty(color1, value, () => color1 = value); }
}
// TODO: same here
public Brush Color2 { get; set; }
public void ChangeColor{//change color1 or color2};
}
Also colors don't usually go into ViewModels. The ViewModel should have some business logic property that you can base the color of the TextBox from XAML, like IsNameAvailable.
You need to register the Property.
public static readonly DependencyProperty Custom_Text_Field_Color_Property =
DependencyProperty.Register("Custom_Text_Field_Color", typeof(Brush),
typeof(Class_Name), new UIPropertyMetadata(null));
public Brush Custom_Text_Field_Color
{
get { return (Brush)GetValue(Custom_Text_Field_Color_Property); }
set { SetValue(Custom_Text_Field_Color_Property, value); }
}
Use the Control Name (i.e., Class Name) for typeof(Class_Name).
In you case class NotificationBase is a custom class, you can use is or not.
I only explain the MVVM design pattern in basically.
In ViewModel, it should be implement Interface INotifyPropertyChanged, and when set property, to trigger event PropertyChanged.
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)));
}
}
}
}
Under sample will demo this MVVM design pattern.
https://code.msdn.microsoft.com/How-to-achieve-MVVM-design-2bb5a580

C# custom listbox GUI

I have a list of classes, but different children have different properties that need to be displayed.
What I want to achieve is to have a listbox-type control in the gui which enables each child to display it's properties the way it wants to - so not using the same pre-defined columns for every class.
I envisage something like the transmission interface (below), where each class can paint it's own entry, showing some text, progress bar if relevant, etc.
How can this be achieved in C#?
Thanks for any help.
Let your list items implement an interface that provides everything needed for the display:
public interface IDisplayItem
{
event System.ComponentModel.ProgressChangedEventHandler ProgressChanged;
string Subject { get; }
string Description { get; }
// Provide everything you need for the display here
}
The transmission objects should not display themselves. You should not mix domain logic (business logic) and display logic.
Customized ListBox:
In order to do display listbox items your own way, you will have to derive your own listbox control from System.Windows.Forms.ListBox. Set the DrawMode property of your listbox to DrawMode.OwnerDrawFixed or DrawMode.OwnerDrawVariable (if the items are not of the same size) in the constructor. If you use OwnerDrawVariable then you will have to override OnMeasureItem as well, in order to tell the listbox the size of each item.
public class TransmissionListBox : ListBox
{
public TransmissionListBox()
{
this.DrawMode = DrawMode.OwnerDrawFixed;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index >= 0 && e.Index < Items.Count) {
var displayItem = Items[e.Index] as IDisplayItem;
TextRenderer.DrawText(e.Graphics, displayItem.Subject, e.Font, ...);
e.Graphics.DrawIcon(...);
// and so on
}
e.DrawFocusRectangle();
}
}
You can let your original transmission class implement IDisplayItem or create a special class for this purpose. You can also have different types of objects in the list, as long as they implement the interface. The point is, that the display logic itself is in the control, the transmission class (or whatever class) only provides the information required.
Example:
Because of the ongoing discussion with Mark, I have decided to include a full example here. Let's define a model class:
public class Address : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
if (_Name != value) {
_Name = value;
OnPropertyChanged("Name");
}
}
}
private string _City;
public string City
{
get { return _City; }
set
{
if (_City != value) {
_City = value;
OnPropertyChanged("City");
OnPropertyChanged("CityZip");
}
}
}
private int? _Zip;
public int? Zip
{
get { return _Zip; }
set
{
if (_Zip != value) {
_Zip = value;
OnPropertyChanged("Zip");
OnPropertyChanged("CityZip");
}
}
}
public string CityZip { get { return Zip.ToString() + " " + City; } }
public override string ToString()
{
return Name + "," + CityZip;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
Here is a custom ListBox:
public class AddressListBox : ListBox
{
public AddressListBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
ItemHeight = 18;
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
const TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter;
if (e.Index >= 0) {
e.DrawBackground();
e.Graphics.DrawRectangle(Pens.Red, 2, e.Bounds.Y + 2, 14, 14); // Simulate an icon.
var textRect = e.Bounds;
textRect.X += 20;
textRect.Width -= 20;
string itemText = DesignMode ? "AddressListBox" : Items[e.Index].ToString();
TextRenderer.DrawText(e.Graphics, itemText, e.Font, textRect, e.ForeColor, flags);
e.DrawFocusRectangle();
}
}
}
On a form, we place this AddressListBox and a button. In the form, we place some initializing code and some button code, which changes our addresses. We do this in order to see, if our listbox is updated automatically:
public partial class frmAddress : Form
{
BindingList<Address> _addressBindingList;
public frmAddress()
{
InitializeComponent();
_addressBindingList = new BindingList<Address>();
_addressBindingList.Add(new Address { Name = "Müller" });
_addressBindingList.Add(new Address { Name = "Aebi" });
lstAddress.DataSource = _addressBindingList;
}
private void btnChangeCity_Click(object sender, EventArgs e)
{
_addressBindingList[0].City = "Zürich";
_addressBindingList[1].City = "Burgdorf";
}
}
When the button is clicked, the items in the AddressListBox are updated automatically. Note that only the DataSource of the listbox is defined. The DataMember and ValueMember remain empty.
yes, if you use WPF it is quite easy to do this. All you have to do is make a different DataTemplate for your different types.
MSDN for data templates
Dr. WPF for Items Control & Data Templates

BindingSource with Generic SubClass in Windows Forms

I'm attempting to do what I considered simple data binding between a BindingSource and a ComboBox. I run into issues when the class I am using as the DataSource of the BindingSource has a property that is an instance of a generic class.
I have the following generic class:
public class GenericClass<T>
{
public T Code { get; set; }
public string Description { get; set; }
public override string ToString()
{
return Description;
}
}
I have a class that has an integer Code:
public class IntegerClass : GenericClass<int>
{
// Nothing unique here, for simple test.
}
I also have the class that is set to the BindingSource's DataSource:
public class ClassBindingClass : INotifyProperty Changed
{
private int _id;
private IntegerClass _choice;
private string _name;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public IntegerClass Choice
{
get { return _choice; }
set
{
_choice = value;
OnPropertyChanged("Choice");
}
}
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertName));
}
}
On my form I create a collection of IntegerClass and set my combobox's datasource as that collection. (This part works fine, the combo box displays the values appropriately.) Then I set the combobox's SelectedValue Binding to the BindingSource's Choice property updating on OnPropertyChanged.
If I replace IntegerClass with a non-generic class when you select a value in the combo box the BindingSource's Choice property changes the NotifyPropertyChanged event is fired and on my form I can update a label saying "Choice has changed!".
When the IntegerClass is part of the ClassBindingClass this no longer works and instead I cannot navigate out of the combo box and instead get a FormatException.
Is what I want to do possible? Can databinding handle generics?
You mention SelectedValue... but your source (and the bound property) are both IntegerClass - so it isn't a value you want to bind, but the item itself. Unfortunately, there is no ComboBox.SelectedItemChanged so you might need to hack it a bit to get 2-way binding...
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
IntegerClass[] choices = new[] {
new IntegerClass { Code = 123, Description = "a b c"},
new IntegerClass { Code = 456, Description = "d e f"},
new IntegerClass { Code = 789, Description = "g h i"},
};
ComboBox cbo = new TwoWayComboBox();
cbo.DropDownStyle = ComboBoxStyle.DropDownList;
cbo.DataSource = choices;
Form form = new Form();
ClassBindingClass obj = new ClassBindingClass();
cbo.DataBindings.Add("SelectedItem", obj, "Choice", true, DataSourceUpdateMode.OnPropertyChanged);
form.DataBindings.Add("Text", obj, "Choice", true, DataSourceUpdateMode.OnPropertyChanged); // show it
form.Controls.Add(cbo);
Application.Run(form);
}
}
class TwoWayComboBox : ComboBox {
public new object SelectedItem
{
get { return base.SelectedItem; }
set { base.SelectedItem = value; }
}
private static readonly object SelectedItemChangedKey = new object();
public event EventHandler SelectedItemChanged {
add { Events.AddHandler(SelectedItemChangedKey, value);}
remove { Events.RemoveHandler(SelectedItemChangedKey, value);}
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[SelectedItemChangedKey];
if (handler != null) { handler(this, EventArgs.Empty); }
base.OnSelectedIndexChanged(e);
}
}

Categories

Resources