I have a class CustomControl which inherits from System.Windows.Forms.Control.
I will also create a new class named GraphicsData which will have all the graphical information about my CustomControl (I need this because it's easier to serialize the data for saving it in a DB, json, etc.)
The CustomControl object will get the GraphicsData at the initialization(in the constructor) and I want it to get all the properties that have a value in GraphicsData (sometimes I don't want to initialize all of the properties from GraphicsData and I want them to remain the default from System.Windows.Forms.Control class).
The problem is that most of the proprierties are not nullable and I cannot check if they are null so I can't do a simple:
customControl.BackColor = graphicsData.BackColor.HasValue ? graphicsData.BackColor.Value : BackColor;
I can of course work this around if I create my own Nullable class but this got really ugly and hard to understand the code. Also, it is very hard to add a new property when needed.
Now, what I did and I think this is a much cleaner way is the following:
GraphicsData class:
public class GraphicsData : INotifyPropertyChanged
{
private readonly List<string> _initializedProperties = new List<string>();
public List<string> InitializedProperties { get { return _initializedProperties; } }
public event PropertyChangedEventHandler PropertyChanged;
private Size _size;
private Point _location;
private AnchorStyles _anchor;
private Color _backColor;
private Image _backgroundImage;
private Cursor _cursor;
private Font _font;
private Color _foreColor;
private bool _enabled;
private bool _visible;
public Size Size
{
get { return _size; }
set
{
_size = value;
OnPropertyChanged("Size");
}
}
public Point Location
{
get { return _location; }
set
{
_location = value;
OnPropertyChanged("Location");
}
}
public AnchorStyles Anchor
{
get { return _anchor; }
set
{
_anchor = value;
OnPropertyChanged("Anchor");
}
}
public Color BackColor
{
get { return _backColor; }
set
{
_backColor = value;
OnPropertyChanged("BackColor");
}
}
public Image BackgroundImage
{
get { return _backgroundImage; }
set
{
_backgroundImage = value;
OnPropertyChanged("BackgroundImage");
}
}
public Cursor Cursor
{
get { return _cursor; }
set
{
_cursor = value;
OnPropertyChanged("Cursor");
}
}
public Font Font
{
get { return _font; }
set
{
_font = value;
OnPropertyChanged("Font");
}
}
public Color ForeColor
{
get { return _foreColor; }
set
{
_foreColor = value;
OnPropertyChanged("ForeColor");
}
}
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
OnPropertyChanged("Enabled");
}
}
public bool Visible
{
get { return _visible; }
set
{
_visible = value;
OnPropertyChanged("Visible");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (!_initializedProperties.Contains(propertyName))
_initializedProperties.Add(propertyName);
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
And in my custom control I have a method:
public void LoadGraphics()
{
var initializedProperties = graphics.InitializedProperties;
foreach (string propertyName in initializedProperties)
{
var value = graphics.GetType()
.GetProperty(propertyName)
.GetValue(graphics, null);
_customControl.GetType()
.GetProperty(propertyName)
.SetValue(_customControl, value, null);
}
}
Basically, I created a List named InitializedProperties and in the properties "set" I add the property in the list.
After that, using reflection in my CustomControl, I can load all the initialized properties.
I implemented the INotifyPropertyChanged because I also want to change the customControl properties each time a property is changed in GraphicsData.
Is this the proper way to do what I want ? I don't think the reflection code is that readable and I am concerned about the performance.
Using nullable values is a much easier method for achieving this.
C# already has a built-in Nullable class, but it also offers a simple way to make a value nullable without the excess verbosity that the Nullable class introduces: ?.
All of your values can be made nullable by appending the ? operator to the value types:
private Size? _size;
private Point? _location;
private AnchorStyles? _anchor;
private Color? _backColor;
private Image _backgroundImage;
private Cursor _cursor;
private Font _font;
private Color? _foreColor;
private bool? _enabled;
private bool? _visible;
Your LoadGraphics method can easily check to see if the GraphicsData property has a non-null value, and set the corresponding control property if so.
public void LoadGraphics(GraphicsData gfx)
{
// It may be permissible to utilize a null value for BackgroundImage!
// In this case, utilizing a separate field (IsBackgroundImageSet) may be a necessary
if (gfx.BackgroundImage != null) { _customControl.BackgroundImage = gfx.BackgroundImage; }
if (gfx.Size != null) { _customControl.Size = gfx.Size.Value; }
if (gfx.Location != null) { _customControl.Location = gfx.Location.Value }
if (gfx.Anchor != null) { _customControl.Anchor = gfx.Anchor.Value; }
if (gfx.BackColor != null) { _customControl.BackColor = gfx.BackColor .Value; }
if (gfx.Cursor != null) { _customControl.Cursor = gfx.Cursor; }
if (gfx.Font != null) { _customControl.Font = gfx.Font; }
if (gfx.Color != null) { _customControl.Color = gfx.Color.Value; }
if (gfx.Enabled != null) { _customControl.Enabled = gfx.Enabled.Value; }
if (gfx.Visible != null) { _customControl.Visible = gfx.Visible.Value; }
}
Related
This is the XAML of the radio. Nothing else is editing this. Once this is set it is not changing. But somehow no matter what it is setting the XML to "false".
Here is how I save the XML file (works just fine).
There are 3 radio buttons, as you can see, that I am trying to get set to false or true but they all just get saved as false.
<RadioButton x:Name="sx80" Content="Cisco SX80" HorizontalAlignment="Left" Margin="701,244,0,0" VerticalAlignment="Top" GroupName="codecType" TabIndex="17" FontWeight="Normal" Height="25" Width="95" Padding="0,2"/>
class SaveXml
{
public static void savedata(object obj, string filename)
{
XmlSerializer sr = new XmlSerializer(obj.GetType());
TextWriter writer = new StreamWriter(filename);
sr.Serialize(writer, obj);
writer.Close();
}
}
Here is the main class that tells it what information we are saving to the XML file.
public class information
{
private string city;
private string chairCount;
private string stateSelect;
private string HostNameIPTyped;
private string VTCmac;
private string vtcUser;
private string vtcPass;
private string VTCserial;
private string AssetTag;
private string SIPURI;
private string SystemName;
private string firstName;
private string lastName;
private string contactPhone;
private string provisionerName;
private string provisionerInitials;
private string provisionDate;
private bool sx80;
private bool codecPlus;
private bool codecPro;
public string postcity
{
get { return city; }
set { city = value; }
}
public string postchairCount
{
get { return chairCount; }
set { chairCount = value; }
}
public string poststateSelect
{
get { return stateSelect; }
set { stateSelect = value; }
}
public string postHostNameIPTyped
{
get { return HostNameIPTyped; }
set { HostNameIPTyped = value; }
}
public string postVTCmac
{
get { return VTCmac; }
set { VTCmac = value; }
}
public string postvtcUser
{
get { return vtcUser; }
set { vtcUser = value; }
}
public string postvtcPass
{
get { return vtcPass; }
set { vtcPass = value; }
}
{ e164 = value; }
}
public string postVTCserial
{
get { return VTCserial; }
set { VTCserial = value; }
}
public string postAssetTag
{
get { return AssetTag; }
set { AssetTag = value; }
}
public string postSIPURI
{
get { return SIPURI; }
set { SIPURI = value; }
}
public string postSystemName
{
get { return SystemName; }
set { SystemName = value; }
}
public string postfirstName
{
get { return firstName; }
set { firstName = value; }
}
public string postlastName
{
get { return lastName; }
set { lastName = value; }
}
public string postcontactPhone
{
get { return contactPhone; }
set { contactPhone = value; }
}
public string postprovisionerName
{
get { return provisionerName; }
set { provisionerName = value; }
}
public string postprovisionerInitials
{
get { return provisionerInitials; }
set { provisionerInitials = value; }
}
public string postprovisionDate
{
get { return provisionDate; }
set { provisionDate = value; }
}
public bool postsx80
{
get { return sx80; }
set { sx80 = value; }
}
public bool postcodecPlus
{
get { return codecPlus; }
set { codecPlus = value; }
}
public bool postcodecPro
{
get { return codecPro; }
set { codecPro = value; }
}
}
The code you posted doesn't show any data binding on the RadioButton or how you've set your DataContext. But you said in the comments that the strings are working so I assume you've set the DataContext somewhere. If you can update your question to show how your Window/View is bound to the information object it will be easier to give you a more accurate solution. You also said the following in one of your comments:
Yes, it is actually being saved as false. If it didn't find a value it would just show nothing. :-) <postsx80>false</postsx80>
The default value for a bool is actually false, so even if no value is retrieved from your RadioButton, your XML file will still show false.
Your RadioButton's would normally be bound like this, depending on how your DataContext is set. Notice the Binding in the IsChecked property. The Mode=TwoWay means that the UI can set the value of the property and not just read it:
<RadioButton x:Name="sx80" Content="Cisco SX80" IsChecked="{Binding Info.postsx80, Mode=TwoWay}" />
In the code behind of this Window I have created a public property called Info which contains an instance of your information class. The RadioButton above is bound the the postsx80 property of this information instance so you would need to pass this instance to your savedata method like below.
public partial class MainWindow : Window
{
public information Info { get; set; } = new information(); // The UI is bound to this instance
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // I've set the Window's DataContext to itself
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SaveXml.savedata(Info, "somefile.xml");
}
}
You should also implement INotifyPropertyChanged which will notify the UI when a property's value has changed. For example your information class could look like this:
// You will need to add the following namespaces
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace YourAppsNamespace
{
public class information : INotifyPropertyChanged // Implement the INotifyPropertyChanged interface
{
private bool sx80;
public bool postsx80
{
get { return sx80; }
set {
sx80 = value;
OnPropertyChanged(); // Notify the UI that this property's value has changed
}
}
// This code raises the event to notify the UI which property has changed
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
You would need to add OnPropertyChanged() to the setters of all of your properties.
You also mentioned in the comments that you don't know how to use auto properties. An auto property is basically a shorter way to write a property when there are no additional actions which need to be performed when getting or setting a value. For example, this:
private bool someBool;
public bool SomeBool
{
get { return someBool; }
set { someBool = value; }
}
Would just become:
public bool SomeBool { get; set; }
There is no need to create the private variable or define the body of the getter and setter. This is handled automatically for you. This is only suitable if you don't need to perform any additional actions in the getter or setter. So in my example above where we need to call OnPropertyNotifyChanged() in the setter, you wouldn't be able to use an auto property.
An additional tip is that you can simply type prop in Visual Studio and press Tab twice to insert an auto property without having to type it out yourself. You then simply change the data type, press Tab again to move to the name and change that. The same can be done for a full property like the ones you wrote by typing propfull.
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 have a WPF application using MVVM. I have the IsChecked value bound to a boolean on my model instance on my ViewModel. I also need to bind a method on the ViewModel to the Checked and Unchecked events. (This is so I can track unsaved changes and change the background to give my users visual indication of the need to save. I tried:
<CheckBox
Content="Enable"
Margin="5"
IsChecked="{Binding Enabled}"
Checked="{Binding ScheduleChanged}"
Unchecked="{Binding ScheduleChanged}"
/>
But I get a 'Provide value on 'System.Windows.Data.Binding' threw an exception.' error. Advice?
Here is the Model I am working with:
public class Schedule : IEquatable<Schedule>
{
private DateTime _scheduledStart;
private DateTime _scheduledEnd;
private bool _enabled;
private string _url;
public DateTime ScheduledStart
{
get { return _scheduledStart; }
set
{
_scheduledStart = value;
}
}
public DateTime ScheduledEnd
{
get { return _scheduledEnd; }
set
{
if(value < ScheduledStart)
{
throw new ArgumentException("Scheduled End cannot be earlier than Scheduled Start.");
}
else
{
_scheduledEnd = value;
}
}
}
public bool Enabled
{
get { return _enabled; }
set { _enabled = value; }
}
public string Url
{
get { return _url; }
set { _url = value; }
}
public bool Equals(Schedule other)
{
if(this.ScheduledStart == other.ScheduledStart && this.ScheduledEnd == other.ScheduledEnd
&& this.Enabled == other.Enabled && this.Url == other.Url)
{
return true;
}
else
{
return false;
}
}
}
My viewModel contains a property that has an ObservableCollection. An ItemsControl binds to the collection and generates a list. So my ViewModel sort of knows about my Model instance, but wouldn't know which one, I don't think.
Checked and Unchecked are events, so you can not bind to them like you can IsChecked, which is a property. On a higher level it is also probably wise for your view model not to know about a checkbox on the view.
I would create an event on the view model that fires when Enabled is changed, and you can subscribe to that and handle it any way you like.
private bool _enabled;
public bool Enabled
{
get
{
return _enabled;
}
set
{
if (_enabled != value)
{
_enabled = value;
RaisePropertyChanged("Enabled");
if (EnabledChanged != null)
{
EnabledChanged(this, EventArgs.Empty);
}
}
}
}
public event EventHandler EnabledChanged;
// constructor
public ViewModel()
{
this.EnabledChanged += This_EnabledChanged;
}
private This_EnabledChanged(object sender, EventArgs e)
{
// do stuff here
}
You should be able to just handle this in the setter for Enabled...
public class MyViewModel : ViewModelBase
{
private bool _isDirty;
private bool _enabled;
public MyViewModel()
{
SaveCommand = new RelayCommand(Save, CanSave);
}
public ICommand SaveCommand { get; }
private void Save()
{
//TODO: Add your saving logic
}
private bool CanSave()
{
return IsDirty;
}
public bool IsDirty
{
get { return _isDirty; }
private set
{
if (_isDirty != value)
{
RaisePropertyChanged();
}
}
}
public bool Enabled
{
get { return _enabled; }
set
{
if (_enabled != value)
{
_enabled = value;
IsDirty = true;
}
//Whatever code you need to raise the INotifyPropertyChanged.PropertyChanged event
RaisePropertyChanged();
}
}
}
You're getting a binding error because you can't bind a control event directly to a method call.
Edit: Added a more complete example.
The example uses the MVVM Lite framework, but the approach should work with any MVVM implementation.
i'm trying to implement INotifyPropertyChanged within singelton class.
Here is my code:
public class plc : INotifyPropertyChanged
{
private static plc instance;
public plc()
{
}
public static plc Instance
{
get
{
if (instance == null)
{
instance = new plc();
}
return instance;
}
set
{
instance = value;
}
}
private static string _plcIp{get; set;}
public string plcIp
{
get
{
return _plcIp;
OnPropertyChanged();
}
set
{
_plcIp = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
I'm getting error unreachable code deleted and of course NotifyPropertyChange isn't working
It's because you are calling OnPropertyChanged(); after you return _plcIp;.
It should be called after you set the value. i.e.:
public string plcIp
{
get
{
return _plcIp;
}
set
{
if (value != _plcIp)
{
_plcIp = value;
OnPropertyChanged();
}
}
}
You should also check that the value is actually changing in the setter before raising the event.
There are several issues in your code:
if you are implementing singleton, then constructor of class should be private
use fields instead of private properties
properties should not be static (you are using singleton)
verify if property value really changed before raising OnPropertyChanged event
raise event before returning property value
use PascalNames for class name and properties names
raise event from setter instead of getter
Code:
public class Plc : INotifyPropertyChanged {
private static Plc _instance;
private Plc() { } // constructor should be private
public static Plc Instance
{
get
{
if (_instance == null)
_instance = new Plc();
return _instance;
} // you don't need setter
}
private string _plcIp; // instance field instead of static property
public string PlcIp
{
get { return _plcIp; }
set
{
if (_plcIp == value)
return; // check if value changed
_plcIp = value; // change value
OnPropertyChanged(); // raise event
}
}
// ...
}
This contains the error :
public string plcIp
{
get
{
return _plcIp;
OnPropertyChanged(); //This row..
}
set { _plcIp = value; }
}
It's in the Set method you want the update in the UI, not when you get the value.
Something like this :
public string plcIp
{
get { return _plcIp; }
set { _plcIp = value; OnPropertyChanged(); }
}
Just stumbled upon propertyGrid and its awesome! However, i have one task that i cant find how to do with it:
I have a class which has a type. Based on type, it has different properties available. I keep it in one class (not multiple inherited classes) for simplicity sake (there are ten types but they mostly have the same properties).
For example, i have a class MapObject which can have string type equal "player" or "enemy". For "enemy", property "name" is used, but for "player" it is blank (not used).
When i select two objects, one of which is of type "player" and other of type "enemy", i want property "name" to only "count" for the "enemy". So, i want propertyGrid to show the name of the object that has type="enemy", and when it (name property) is changed in Grid, only assign it to the object of type "enemy".
Is this possible to do?
Depending on whose PropertyGrid you are using, toggling the Browsable attribute may do what you want. See my answer here for how to do that at runtime.
If, like me, you are using the Xceed PropertyGrid then only changing the Browsable attribute at runtime once the control has loaded doesn't do anything. Instead, I also had to modify the PropertyDefinitions collection. Here is an extension method for doing that:
/// <summary>
/// Show (or hide) a property within the property grid.
/// Note: if you want to initially hide the property, it may be
/// easiest to set the Browable attribute of the property to false.
/// </summary>
/// <param name="pg">The PropertyGrid on which to operate</param>
/// <param name="property">The name of the property to show or hide</param>
/// <param name="show">Set to true to show and false to hide</param>
public static void ShowProperty(this PropertyGrid pg, string property, bool show)
{
int foundAt = -1;
for (int i=0; i < pg.PropertyDefinitions.Count; ++i)
{
var prop = pg.PropertyDefinitions[i];
if (prop.Name == property)
{
foundAt = i;
break;
}
}
if (foundAt == -1)
{
if (show)
{
pg.PropertyDefinitions.Add(
new Xceed.Wpf.Toolkit.PropertyGrid.PropertyDefinition()
{
Name = property,
}
);
}
}
else
{
if (!show)
{
pg.PropertyDefinitions.RemoveAt(foundAt);
}
}
}
In case the above does not work for you, the following may work better and is simpler anyway. It also doesn't use deprecated properties like the code above did...
public static void ShowProperty(this PropertyGrid pg, string property, bool show)
{
for (int i = 0; i < pg.Properties.Count; ++i)
{
PropertyItem prop = pg.Properties[i] as PropertyItem;
if (prop.PropertyName == property)
{
prop.Visibility = show ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
break;
}
}
}
This is a design pattern known as the state pattern. It is pretty easy to implement and you do not need property grids. http://www.dofactory.com/Patterns/PatternState.aspx
I made it with my own custom attribute:
public class VisibilityAttribute : Attribute
{
public bool IsVisible { get; set; }
public VisibilityAttribute(bool isVisible)
{
IsVisible = isVisible;
}
}
Then my data model:
public abstract class BaseSettings: INotifyPropertyChanged
{
public void SetVisibilityProperty(string propertyName, bool isVisible)
{
var theDescriptor = TypeDescriptor.GetProperties(this.GetType())[propertyName];
var theDescriptorVisibilityAttribute = (VisibilityAttribute)theDescriptor.Attributes[typeof(VisibilityAttribute)];
if (theDescriptorVisibilityAttribute == null) return;
theDescriptorVisibilityAttribute.IsVisible = isVisible;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
public class ThrottleSettings : BaseSettings
{
private ThrottleType _throttleType = ThrottleType.SmartThrottle;
[PropertyOrder(1)]
public ThrottleType ThrottleType
{
get
{
return _throttleType;
}
set
{
if (value == ThrottleType.FullThrottle)
{
SetVisibilityProperty(nameof(FullThrottleTimeInMilliseconds), true);
SetVisibilityProperty(nameof(ThumbnailThrottleTimeInMilliseconds), false);
}
else if (value == ThrottleType.SmartThrottle)
{
SetVisibilityProperty(nameof(FullThrottleTimeInMilliseconds), false);
SetVisibilityProperty(nameof(ThumbnailThrottleTimeInMilliseconds), true);
}
else if (value == ThrottleType.NoThrottle)
{
SetVisibilityProperty(nameof(FullThrottleTimeInMilliseconds), false);
SetVisibilityProperty(nameof(ThumbnailThrottleTimeInMilliseconds), false);
}
_throttleType = value;
}
}
private int _fullThrottleTime = 100;
[PropertyOrder(2)]
[Visibility(false)]
[Description("Specifies full throttle time (in milliseconds).")]
public int FullThrottleTimeInMilliseconds
{
get
{
return _fullThrottleTime;
}
set
{
if (value < 0) return;
_fullThrottleTime = value;
}
}
private int _thumbnailThrottleTime = 0;
[PropertyOrder(3)]
[Visibility(true)]
[Description("Specifies thumbnail throttle time (in milliseconds).")]
public int ThumbnailThrottleTimeInMilliseconds
{
get
{
return _thumbnailThrottleTime;
}
set
{
if (value < 0) return;
_thumbnailThrottleTime = value;
}
}
}
Finally I subscribed to 'propertyGrid_PropertyValueChanged' event and call there my method:
private void _propertyGrid_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e)
{
RefreshVisibility(_propertyGrid.Properties);
}
Here is method itself:
private void RefreshVisibility(IList properties)
{
foreach (PropertyItem property in properties)
{
var visibilityAttribute = GetVisibilityAttribute(property);
if (visibilityAttribute != null)
{
if (visibilityAttribute.IsVisible)
property.Visibility = Visibility.Visible;
else
property.Visibility = Visibility.Collapsed;
}
RefreshVisibility(property.Properties);
}
}