Why aren't my data-bound user settings saving? - c#

I have the following:
MainWindow:
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TestApp"
xmlns:settings="clr-namespace:TestApp.Settings"
mc:Ignorable="d" Title="MainWindow" Height="350" Width="525">
<Grid>
<ItemsControl>
<ItemsControl.ItemsSource>
<Binding>
<Binding.Source>
<CollectionViewSource Source="{Binding Source={x:Static settings:CustomSettings.Default}, Path=coll}" />
</Binding.Source>
</Binding>
</ItemsControl.ItemsSource>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Name}" />
<Button Grid.Column="1" Click="Button_Click" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
Code-Behind:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace TestApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
if (Settings.CustomSettings.Default.coll == null)
{
Settings.CustomSettings.Default.coll = new ObservableCollection<BasicClass>();
Settings.CustomSettings.Default.coll.Add(new BasicClass("String1"));
Settings.CustomSettings.Default.coll.Add(new BasicClass("String2"));
Settings.CustomSettings.Default.coll.Add(new BasicClass("String3"));
}
Settings.CustomSettings.Default.Save();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Settings.CustomSettings.Default.Save();
foreach (BasicClass item in Settings.CustomSettings.Default.coll)
{
MessageBox.Show(item.Name);
}
}
}
public class BasicClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private string name;
public string Name
{
get { return name; }
set
{
if (value != name)
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
public BasicClass() { }
public BasicClass(string Name)
{
this.Name = Name;
}
}
}
Settings:
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics;
namespace TestApp.Settings
{
internal sealed partial class CustomSettings : ApplicationSettingsBase
{
private static CustomSettings defaultInstance = ((CustomSettings)(Synchronized(new CustomSettings())));
public static CustomSettings Default
{
get
{
return defaultInstance;
}
}
[UserScopedSetting()]
[DebuggerNonUserCode()]
public ObservableCollection<BasicClass> coll
{
get
{
return ((ObservableCollection<BasicClass>)(this["coll"]));
}
set
{
this["coll"] = value;
}
}
}
}
How it works:
The app present three controls consisting of a TextBox and a Button. These are part of an ItemsControl whose source is bound to a user setting 'coll', of type ObservableCollection<BasicClass>. BasicClass has one property, 'Name', which appears in the TextBox via data-binding.
Expected behaviour:
I change the text in a TextBox, then click the corresponding Button. This would then save the new value in 'coll', and then present a MessageBox sequence demonstrating that this has indeed been changed. I restart the app, and my value is showing the newly saved value.
Actual behaviour:
I change the text, I click the Button, the MessageBox sequence shows me that the value is now stored in the user settings (and should therefore have been saved). However, when I restart the app, I see the original value, not the saved one.
An anomaly(?):
If I click the button twice instead of once (going through the MessageBox sequence twice), when I restart the value has now been successfully saved.

EDIT (original answer below):
While I suspect implementing IBindableComponent on a subclass of ObservableCollection might work, I don't recommend it. If you're just storing strings, System.Collections.Specialized.StringCollection might help you.
But in general, I don't think it makes much sense to update your application settings each time something changes. Instead, load them during application startup into your view model (e.g. an ObservableCollection) and move them back to the application settings when closing. This way, the values only need to be deserialized and serialized once.
The effect you mention in your comment about setting the value to itself works (it seems) because the list is re-serialized when you set it. It appears, ApplicationSettingsBase is storing a serialized copy of every value you provide, and therefore can't react to changes in your original object. When you provide the value again, it overwrites its copy with a serialized version of the new state of your object. However, if you serialize the list every time a user makes a change, it will impact your app's performance, once the list gets longer.
This might be interesting to you as well:
How to store int[] array in application Settings
And it seems unnecessary to subclass ApplicationSettingsBase yourself, see https://social.msdn.microsoft.com/Forums/en-US/4e299ed8-8e3a-408e-b900-eb6738fe0775/persist-and-restore-application-state?forum=wpf
ORIGINAL:
I'm not familiar with the ApplicationSettingsBase, but perhaps this helps https://msdn.microsoft.com/en-in/library/8eyb2ct1(en-us).aspx:
You can only bind an application setting to a component that supports the IBindableComponent interface. Also, the component must implement a change event for a specific bound property, or notify application settings that the property has changed through the INotifyPropertyChanged interface. If the component does not implement IBindableComponent and you are binding through Visual Studio, the bound properties will be set the first time, but will not update. If the component implements IBindableComponent but does not support property change notifications, the binding will not update in the settings file when the property is changed.
It seems like it has to do with the fact that only serialized versions of your settings are stored and therefore changes within the list are not recognized (because the reference itself does not change). Note that when you replace the list entirely upon clicking a button, the new list's values are stored.

Related

Changing background proprieties of multiple controls using a button

I am working on an app that has a lot of buttons on the main window.
The buttons have been programmed individually to change color when pressed, and save that those colors using the user settings from Visual Studio.
More exactly, when the user presses a button once, its background changes to red, and when he presses it again the background changes to green.
Edited for mm8:
Here is the xaml (sample):
<Window x:Class="test2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:test2"
xmlns:properties="clr-namespace:test2.Properties"
mc:Ignorable="d"
Title="MainWindow" WindowStartupLocation="CenterScreen" Height="850" Width="925">
<Grid x:Name="theGrid">
<Button x:Name="Button0" HorizontalAlignment="Left" Margin="197,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color0, Mode=TwoWay}" Click="Button0_Click"/>
<Button x:Name="Button1" HorizontalAlignment="Left" Margin="131,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color1, Mode=TwoWay}" Click="Button1_Click"/>
<Button x:Name="Button2" HorizontalAlignment="Left" Margin="263,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color2, Mode=TwoWay}" Click="Button2_Click"/>
<Button x:Name="Reset" Content="Reset" HorizontalAlignment="Left" Margin="832,788,0,0" VerticalAlignment="Top" Width="75" Click="Reset_Click" />
</Grid>
</Window>
And this is the code I implemented into each button's click event:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace test2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button0_Click(object sender, RoutedEventArgs e)
{
if (Properties.Settings.Default.Color0 == "Green")
{
Properties.Settings.Default.Color0 = "Red";
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.Color0 = "Green";
Properties.Settings.Default.Save();
}
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
if (Properties.Settings.Default.Color1 == "Green")
{
Properties.Settings.Default.Color1 = "Red";
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.Color1 = "Green";
Properties.Settings.Default.Save();
}
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
if (Properties.Settings.Default.Color2 == "Green")
{
Properties.Settings.Default.Color2 = "Red";
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.Color2 = "Green";
Properties.Settings.Default.Save();
}
}
private void Reset_Click(object sender, RoutedEventArgs e)
{
foreach (Button button in theGrid.Children.OfType<Button>())
}
}
}
Now, I want to some sort of a Reset button, which when pressed changes the background of all the buttons to the default (not red, nor green).
What I tried to do was to use ideas from this thread and use them as a click event on the reset button, but whenever I do
foreach (Control x in Control.Controls)
or any other method using the "Controls" (this.Controls, etc) I get it underlined with red, saying that the Control class does not have the definition.
Am I doing something wrong? Do you guys have any suggestions as to how I can program that button to change all buttons' background to default?
The short version: you're doing it wrong. I mean, I suspect you already knew that to some extent, because the code didn't work. But looking at your comment that says you'll have 240 buttons, you are really going about this the wrong way.
This answer is meant to walk you through three different options, each moving you closer to what is the best approach for dealing with this scenario.
Starting with your original effort, we can get the code you posted to work mostly as-is. Your main problem is that, having successfully obtained each Button child of your Grid, you cannot just set the Button.Background property. If you do, you will erase the binding that was set up in the XAML.
Instead, you need to reset the values in your source data, and then force the binding target to be updated (because the Settings object does not provide a WPF-compatible property-changed notification mechanism). You can accomplish this by changing your Reset_Click() method to look like this:
private void Reset_Click(object sender, RoutedEventArgs e)
{
Settings.Default.Color0 = Settings.Default.Color1 = Settings.Default.Color2 = "";
Settings.Default.Save();
foreach (Button button in theGrid.Children.OfType<Button>())
{
BindingOperations.GetBindingExpression(button, Button.BackgroundProperty)?.UpdateTarget();
}
}
This is not ideal. It would be much better to not have to access the binding state directly, and instead let WPF deal with updates. In addition, if you look at the debug output, for every time a button is set to the "default" state, a exception is being thrown. That's also not a very good situation.
These issues can be addressed. The first, by moving to an MVVM-style implementation, in which the state of the program is stored independently of the visual part of the program, with the visual part responding to changes in that state. The second, by adding some logic to coerce the invalid string value into something that WPF is happy with.
To accomplish this, it's helpful to have a couple of pre-made helper classes made, one for supporting the view model classes themselves directly, and one for representing a command (which is a better way to deal with user input than handling Click events directly). Those look like this:
class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void _UpdateField<T>(ref T field, T newValue,
Action<T> onChangedCallback = null,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
{
return;
}
T oldValue = field;
field = newValue;
onChangedCallback?.Invoke(oldValue);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class DelegateCommand : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public DelegateCommand(Action execute) : this(execute, null) { }
public DelegateCommand(Action execute, Func<bool> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute?.Invoke() ?? true;
}
public void Execute(object parameter)
{
_execute();
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
These are just examples. The NotifyPropertyChangedBase class is mostly identical to what I use on a day-to-day basis. The DelegateCommand class is a stripped-down version of a more fully-featured implementation I use (mainly, it's missing support for command parameters, since they aren't needed in this particular scenario). There are lots of similar examples on Stack Overflow and the Internet, often built into a library designed to help with WPF development.
With those, we can define some "view model" classes that will represent the state of the program. Note that these classes have practically nothing in them that involves the view per se. The one exception being the use of DependencyProperty.UnsetValue, as a concession to simplicity. It is possible to get rid of even that, along with the "coerce" methods that support that design, as you'll see in the third example, after this one.
First, a view model to represent each individual button's state:
class ButtonViewModel : NotifyPropertyChangedBase
{
private object _color = DependencyProperty.UnsetValue;
public object Color
{
get { return _color; }
set { _UpdateField(ref _color, value); }
}
public ICommand ToggleCommand { get; }
public ButtonViewModel()
{
ToggleCommand = new DelegateCommand(_Toggle);
}
private void _Toggle()
{
Color = object.Equals(Color, "Green") ? "Red" : "Green";
}
public void Reset()
{
Color = DependencyProperty.UnsetValue;
}
}
Then a view model that holds the overall state of the program:
class MainViewModel : NotifyPropertyChangedBase
{
private ButtonViewModel _button0 = new ButtonViewModel();
public ButtonViewModel Button0
{
get { return _button0; }
set { _UpdateField(ref _button0, value); }
}
private ButtonViewModel _button1 = new ButtonViewModel();
public ButtonViewModel Button1
{
get { return _button1; }
set { _UpdateField(ref _button1, value); }
}
private ButtonViewModel _button2 = new ButtonViewModel();
public ButtonViewModel Button2
{
get { return _button2; }
set { _UpdateField(ref _button2, value); }
}
public ICommand ResetCommand { get; }
public MainViewModel()
{
ResetCommand = new DelegateCommand(_Reset);
Button0.Color = _CoerceColorString(Settings.Default.Color0);
Button1.Color = _CoerceColorString(Settings.Default.Color1);
Button2.Color = _CoerceColorString(Settings.Default.Color2);
Button0.PropertyChanged += (s, e) =>
{
Settings.Default.Color0 = _CoercePropertyValue(Button0.Color);
Settings.Default.Save();
};
Button1.PropertyChanged += (s, e) =>
{
Settings.Default.Color1 = _CoercePropertyValue(Button1.Color);
Settings.Default.Save();
};
Button2.PropertyChanged += (s, e) =>
{
Settings.Default.Color2 = _CoercePropertyValue(Button2.Color);
Settings.Default.Save();
};
}
private object _CoerceColorString(string color)
{
return !string.IsNullOrWhiteSpace(color) ? color : DependencyProperty.UnsetValue;
}
private string _CoercePropertyValue(object color)
{
string value = color as string;
return value ?? "";
}
private void _Reset()
{
Button0.Reset();
Button1.Reset();
Button2.Reset();
}
}
The important thing to note is that nowhere in the above does anything try to manipulate the UI objects directly, and yet you have everything there that you'd need to maintain the state of the program as controlled by the user.
With the view models in hand, all that's left is to define the UI:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:l="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<l:MainViewModel/>
</Window.DataContext>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Width="66" Height="26" Background="{Binding Button0.Color}" Command="{Binding Button0.ToggleCommand}"/>
<Button Width="66" Height="26" Background="{Binding Button1.Color}" Command="{Binding Button1.ToggleCommand}"/>
<Button Width="66" Height="26" Background="{Binding Button2.Color}" Command="{Binding Button2.ToggleCommand}"/>
</StackPanel>
<Button Content="Reset" Width="75" HorizontalAlignment="Right" VerticalAlignment="Bottom" Command="{Binding ResetCommand}"/>
</Grid>
</Window>
Some things to note here:
There is no code at all in the MainWindow.xaml.cs file. It's completely unchanged from the default template, with just the parameterless constructor and the call to InitializeComponent(). By moving to an MVVM-style implementation, a lot of the internal plumbing required otherwise just goes away completely.
This code does not hard-code any UI element locations (e.g. by setting Margin values). Instead, it takes advantage of WPF's layout features to place the color buttons in a row in the middle, and to place the reset button in the lower right of the window (that way it's visible no matter what size the window is).
The MainViewModel object is set as the Window.DataContext value. This data context is inherited by any elements within the window, unless overridden by setting it explicitly, or (as you'll see in the third example) because the element is automatically generated in a different context. Binding paths are all relative to this object, of course.
Now, this would probably an okay way to go if you really did only have three buttons. But with 240, you're in for a lot of copy/paste headaches. There are a lot of reasons to follow the DRY ("don't repeat yourself") principle, including convenience and code reliability and maintainability. That all would definitely apply here.
To improve on the MVVM example above, we can do some things:
Save the settings in a collection instead of having an individual setting property for each button.
Maintain a collection of the ButtonViewModel objects instead of having an explicit property for each button.
Use an ItemsControl to present the collection of ButtonViewModel objects instead of declaring a separate Button element for every button.
To accomplish this, the view models will have to change a bit. The MainViewModel replaces the individual properties with a single Buttons property to hold all the button view model objects:
class MainViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<ButtonViewModel> Buttons { get; } = new ObservableCollection<ButtonViewModel>();
public ICommand ResetCommand { get; }
public MainViewModel()
{
ResetCommand = new DelegateCommand(_Reset);
for (int i = 0; i < Settings.Default.Colors.Count; i++)
{
ButtonViewModel buttonModel = new ButtonViewModel(i) { Color = Settings.Default.Colors[i] };
Buttons.Add(buttonModel);
buttonModel.PropertyChanged += (s, e) =>
{
ButtonViewModel model = (ButtonViewModel)s;
Settings.Default.Colors[model.ButtonIndex] = model.Color;
Settings.Default.Save();
};
}
}
private void _Reset()
{
foreach (ButtonViewModel model in Buttons)
{
model.Reset();
}
}
}
You'll notice the handling of the Color property is a little different too. That's because in this example, the Color property is an actual string type instead of object, and I'm using an IValueConverter implementation to handle mapping the string value to what's needed by the XAML elements (more on that in a bit).
The new ButtonViewModel is a little different too. It has a new property, to indicate which button it is (this allows the main view model to know which element of the settings collection the button view model goes with), and the Color property handling is a little simpler, because now we're dealing only with string values, instead of the DependencyProperty.UnsetValue value as well:
class ButtonViewModel : NotifyPropertyChangedBase
{
public int ButtonIndex { get; }
private string _color;
public string Color
{
get { return _color; }
set { _UpdateField(ref _color, value); }
}
public ICommand ToggleCommand { get; }
public ButtonViewModel(int buttonIndex)
{
ButtonIndex = buttonIndex;
ToggleCommand = new DelegateCommand(_Toggle);
}
private void _Toggle()
{
Color = Color == "Green" ? "Red" : "Green";
}
public void Reset()
{
Color = null;
}
}
With our new view models, they can now be hooked up in the XAML:
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:l="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<l:MainViewModel/>
</Window.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding Buttons}" HorizontalAlignment="Center">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<l:ColorStringConverter x:Key="colorStringConverter1"/>
<DataTemplate DataType="{x:Type l:ButtonViewModel}">
<Button Width="66" Height="26" Command="{Binding ToggleCommand}"
Background="{Binding Color, Converter={StaticResource colorStringConverter1}, Mode=OneWay}"/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
<Button Content="Reset" Width="75" HorizontalAlignment="Right" VerticalAlignment="Bottom" Command="{Binding ResetCommand}"/>
</Grid>
</Window>
As before, the main view model is declared as the Window.DataContext value. But, instead of explicitly declaring each button element explicitly, I'm using an ItemsControl element to present the buttons. It has these crucial aspects:
The ItemsSource property is bound to the Buttons collection.
The default panel used for this element would be a vertically-oriented StackPanel, so I've overridden that with a horizontally-oriented one, to achieve the same layout used in the previous examples.
I've declared an instance of my IValueConverter implementation as a resource so that it can be used in the template.
I've declared a DataTemplate as a resource, with the DataType set to the type of the ButtonViewModel. When presenting the individual ButtonViewModel objects, WPF will look in the in-scope resources for a template assigned to that type, and since I've declared one here, it will use that to present the view model object. For each ButtonViewModel object, WPF will create an instance of the content in the DataTemplate element, and will set the DataContext for the root object of that content to the view model object. And finally,
In the template, the binding uses the converter I declared earlier. This allows me to insert a little bit of C# code into the property binding, to allow me to ensure the string value is handled appropriately, i.e. when it's empty the appropriate DependencyProperty.UnsetValue is used, avoiding any runtime exceptions from the binding engine.
Here's that converter:
class ColorStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string text = (string)value;
return !string.IsNullOrWhiteSpace(text) ? text : DependencyProperty.UnsetValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
In this case, the ConvertBack() method is not implemented, because we'll only ever be using the binding in the OneWay mode. We just need to check the string value, and if it's null or empty (or whitespace), we return the DependencyProperty.UnsetValue instead.
Some other notes on this implementation:
The Settings.Colors property is set to type System.Collections.Specialized.StringCollection, and initialized (in the Designer) with three empty string values. The length of this collection determines how many buttons are created. You can, of course, use whatever mechanism you want to track this side of the data if you prefer something else.
With 240 buttons, simply arranging them in a horizontal row may or may not work for you (depending on how large the buttons really will be). You can use other panel objects for the ItemsPanel property; likely candidates include UniformGrid or ListView (with the GridView view), both of which can arrange the elements in an automatically spaced grid.
Since the Button elements are located in some kind of parent Panel, such as for example a StackPanel, you could iterate through its Children collection like this:
foreach(Button button in thePanel.Children.OfType<Button>())
{
//...
}
XAML:
<StackPanel x:Name="thePanel">
<Button x:Name="Button0" HorizontalAlignment="Left" Margin="197,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color0, Mode=TwoWay}" Click="Button0_Click" />
<Button x:Name="Button1" HorizontalAlignment="Left" Margin="131,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Source={x:Static properties:Settings.Default}, Path=Color1, Mode=TwoWay}" Click="Button1_Click" />
<Button x:Name="Button0_Copy" HorizontalAlignment="Left" Margin="563,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Color_0, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" Click="Button0_Copy_Click"/>
<Button x:Name="Button1_Copy" HorizontalAlignment="Left" Margin="497,139,0,0" VerticalAlignment="Top" Width="66" Height="26" Focusable="False" Background="{Binding Color_1, Mode=TwoWay, Source={x:Static properties:Settings.Default}}" Click="Button1_Copy_Click"/>
</StackPanel>

WPF databinding not working despite the target datacontext bound to the correct source memory address

The scenario is very simple here. I'm trying to bind a textbox to a property of a class at runtime:
tb.displayValue.DataContext = p.GetValue(currentNode, null);
xaml for the textbox:
<TextBox Name="displayValue" Grid.Column="1"
Style="{StaticResource propertyTextBoxStyle}"
Text="{Binding Path=DataContext,
RelativeSource={RelativeSource Self},
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}">
</TextBox>
When the application starts, the textbox does get populated with the correct information so the source to target binding is working fine. However, when I try and edit a value in the textbox and then switch focus, the changes are not reflected in the actual data structure. The value would stay on the UI, but as soon as I try to reload the UI from the data structure again it defaults back to the original value.
I suspect the binding is not working correctly at first, but after checking the memory address of tb.displayValue.DataContext and comparing it to the actual memory address of the data structure it's an identical match.
INotifyPropertyChanged has been implemented and I have added the OnPropertyChanged call to every setter. After spending two days trying to debug this issue I think I'm really running out of options here so any suggestion would be appreciated.
The simplest two-way binding works this way: you set the DataContext on your Window to a new instance of your MainWindowViewModel class which implements INotifyPropertyChanged, and you set the binding path on your TextBox to the name of the public property on your ViewModel you want to bind to.
I'm trying to show how you need a public property with a get and set to bind to, and how to properly set the DataContext for your window so that all of the controls within it are able to bind to the public properties available on it.
I've never heard of setting the DataContext of a TextBox directly to the return value from a method before, and it just seems wrong, so maybe you are not going about it the right way, and hopefully this helps you see how it can work.
MainWindow.cs
<Window x:Class="DemoWPFApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:DemoWPFApp1.ViewModels"
Height="300" Width="460" WindowStartupLocation="CenterScreen">
<Window.DataContext>
<vm:MainWindowViewModel />
</Window.DataContext>
<TextBox Name="displayValue" Text="{Binding Path=BoundProperty,
Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
</TextBox>
</Window>
MainWindowViewModel.cs
namespace DemoWPFApp1.ViewModels
{
public class MainWindowViewModel : BaseViewModel
{
private string m_boundProperty;
public string BoundProperty
{
get
{
return m_boundProperty;
}
set
{
m_boundProperty = value; OnPropertyChanged();
}
}
public MainWindowViewModel()
{
BoundProperty = "Some value.";
}
}
}
BaseViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace DemoWPFApp1.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propName = null)
{
var e = PropertyChanged;
if (e != null && propName != null)
{
e.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
}
}

UWP Classic Binding not updating UI after setting bound value from Inputcontrol

To simplify my problem, in my app I want to change the user's input to all uppercase. So "foo" should be displayed as "FOO" when the TextBox loses focus.
My Xaml:
<Page x:Class="App12.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:App12"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.DataContext>
<local:MainViewModel />
</Page.DataContext>
<StackPanel Margin="10,50,10,10" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox Text="{Binding Name1, Mode=TwoWay}" />
<TextBox Text="{x:Bind Path=vm.Name2, Mode=TwoWay}" />
<Button HorizontalAlignment="Center">Just a control for the TextBox to lose focus</Button>
</StackPanel>
</Page>
My ViewModel
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace App12
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
}
private string _name1 = "something";
public string Name1
{
get
{
return _name1;
}
set
{
_name1 = (string)value.ToUpper();
OnPropertyChanged();
}
}
private string _name2 = "something";
public string Name2
{
get
{
return _name2;
}
set
{
_name2 = (string)value.ToUpper();
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged( [CallerMemberName] string propertyName = null )
{
var handler = PropertyChanged;
handler?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
}
}
}
And my code-behind
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App12
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
MainViewModel vm;
public MainPage()
{
this.InitializeComponent();
DataContextChanged += MainPage_DataContextChanged;
}
private void MainPage_DataContextChanged( FrameworkElement sender, DataContextChangedEventArgs args )
{
vm = (MainViewModel)DataContext;
}
}
}
When I use classical binding in a UWP app (First TextBox), this code doesn't work
I see the setter being called, OnNotifyPropertyChanged gets called as well, and the handler is not null. Variable _text gets assigned its new value just fine (all uppercase), but then I never see the getter of public variable Text called.
I've also tried a converter (with ConvertBack implemented), with the same result.
Using x:Bind however (Second TextBox), it does work.
In WPF this also works as expected.
Am I missing something or has Binding changed? According to what Microsoft tells us and what I've seen it shouldn't have.
I found another Q/A in Stackoverflow which says:
The problem here is that the binding system in UWP is "intelligent". For TwoWay bindings, changes to the target will automatically propagate to the source and in this scenario, binding system assumes that the PropertyChanged event will fire for corresponding property in source and it ignores these events. So even you have RaisePropertyChanged or NotifyPropertyChanged in you source, the TextBox still won't update.
BTW I can't figure out how to create a workaround for this problem with the classic TwoWay Binding.

Really simple WPF form data validation - how to?

I'm having this really simple class, lets call it Customer.
It look like this:
namespace TestValidation
{
class Customer
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
if (String.IsNullOrEmpty(value))
{
throw new Exception("Customer name is mandatory.");
}
}
}
}
}
Now, I've created a basic form, where the user can add customers to the database. The form contain simple TextBox, bounded to the Name property of Customer, and an "Add" button.
The XAML code is:
<Window x:Class="TestValidation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestValidation"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Margin="119,86,107,194" Name="CustomerName"
Text="{Binding Path=Customer.Name,
ValidatesOnExceptions=True,
ValidatesOnDataErrors=True,
UpdateSourceTrigger=PropertyChanged,
NotifyOnValidationError=True}"
/>
<Button Content="Add" HorizontalAlignment="Left" Margin="204,176,0,0" VerticalAlignment="Top" Width="74"/>
</Grid>
</Window>
From the setter of the Name property, you can understand that the name is mandatory for me, so I want an validation event to rise if the Name TextBox left blank. By validation rules of WPF - once the user focus out of the textbox, and there's no value over there - it should change the border color to red. For some reason - this is not happening, and I don't have a clue why. What is wrong in my process?
Now, I've read so many good articles about Validation in WPF (like Enforcing Complex Business Data Rules with WPF, Data validation in WPF and Validation in Windows Presentation Foundation), but none of them helped me solving my problem.
Eventually, I want the form to look like the form in Brian Noyes excellent article over the first link (Don't have 10 credits, so I can't attach a photo... sorry).
I'll be grateful if someone can explain to me how it really works.
Important note - I'm working with .Net framework 4, so I need a solution that suits this version.
I would definitely recommend using IDataErrorInfo for WPF validation since WPF already understands how to use it, and its easy to implement.
To start with, add the interface to the class containing the data you want to validate. The required methods will probably look something like this:
public class Customer : IDataErrorInfo
{
...
#region IDataErrorInfo Members
string IDataErrorInfo.Error
{
get { return null; }
}
string IDataErrorInfo.this[string columnName]
{
get
{
if (columnName == "Name")
{
// Validate property and return a string if there is an error
if (string.IsNullOrEmpty(Name))
return "Name is Required";
}
// If there's no error, null gets returned
return null;
}
}
#endregion
}
Next, you need to set ValidatesOnDataErrors=True in your TextBox binding so it runs the validation whenever the Name property changes:
<TextBox Text="{Binding Path=Customer.Name, ValidatesOnDataErrors=True}" ... />
And finally, create a Validation Template in your XAML to tell WPF how to draw a validation error. Here's the style/template I usually use:
<!-- ValidatingControl Style -->
<Style TargetType="{x:Type FrameworkElement}" x:Key="ValidatingControl">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding
Path=(Validation.Errors)[0].ErrorContent,
RelativeSource={x:Static RelativeSource.Self}}" />
</Trigger>
</Style.Triggers>
</Style>
Also, be sure your Customer class implements INotifyPropertyChanged so it correctly responds to UI updates. I don't see that in your code, but often people leave that out for simplicity :)
You did not specify a validation rule. The validation rule would be invoked before the control is left and then can do whatever you want to validate the inputs.
A simple example - and I guess that's what you want to do - is provided here.
Use IDataErrorInfo for validation. this link will help you.
I think the issue might be that your class isn't implementing INotifyPropertyChanged, so isn't binding as you're expecting.
Implement the INotifyPropertyChanged interface, raise an event when the property changed and it should work.
See http://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx for a walkthrough.
<Binding Path=Name UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
http://msdn.microsoft.com/en-us/library/ms752347%28v=vs.110%29.aspx#what_is_data_binding
Please use this blog : prasadcsharp.blogspot.com
Here is something that worked fine with me. No lag or long coding but I used it on double values only. You may change it as you need.
private void search_box_TextChanged(object sender, TextChangedEventArgs e)
{
// box text and background to normal state if user types numbers
search_box.Foreground = Brushes.Black;
search_box.Background = Brushes.White;
if (search_id.IsSelected == true)
{
try
{
//convert while user is typing
if (string.IsNullOrEmpty(search_box.Text)==false)
Convert.ToDouble(search_box.Text);
search_error.Text = null;
}
//if user types a letter or a space or a symbol ====>
catch (Exception)
{
// user cant type any value other than numbers as exception prevents it and clears the box text value <======
search_box.Text = null;
search_box.Foreground = Brushes.White;
search_box.Background = Brushes.Red;
search_error.Text="id is numberic value";
}
}
}
Hope it helps.
1) when you use exceptions for validation, i reccomand to throw the exception before assigning the value to the property backing field, so you refuse it and your data-object (the Customer object in this case) will contain only valid data:
using System;
namespace TestValidation
{
public class Customer
{
private string _name;
public string Name
{
get => this._name;
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("Customer name is mandatory.", nameof(Name));
_name = value;
}
}
}
}
2) By default, WPF data-binding engine ignores the exceptions that are raised in the setter procedure of the data objetc. You correctly set the ValidatesOnExceptions to true in order to instruct the data binding system to react on Exceptions. But, you set the UpdateSourceTrigger on PropertyChanged, thus the update of the property (Name) of the Source object (Customer) is triggered only when the Target property (Text) of the Target element (TextBox) is changed. If you start with an empty TextBox and just tab into it and than tab again away, the Text property has not been changed, so the updating of the Source property (Name) will no be triggered (this will happen even with LostFocus as the UpdateSourceTrigger mode). You can correct this just initializig the Text property to null or String.Empty in the costructor or in the Loaded event handler. This way, the textbox will appear with a red border as soon as the window is rendered. If you set UpdateSourceTrigger to LostFocus (that is the default for TextBox's Text property), the TextBox will appear initially without error, but if you tab in and out, it will be highlighted with the expected red border.
Note: all this works because the Text property of the TextBox use TwoWay as the default binding mode, data can go from target to source.
using System.Windows;
namespace TestValidation
{
public partial class MainWindow: System.Windows.Window
{
public CustomerTest()
{
InitializeComponent();
}
private void window_Loaded(object sender, RoutedEventArgs e)
{
this.txtCustomerName.Text = null;
}
}
}
<Window x:Class="TestValidation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ValidationTests"
Title="MainWindow" Height="350" Width="525"
Loaded="window_Loaded">
<Window.Resources>
<local:Customer x:Key="customer" />
</Window.Resources>
<Grid DataContext="{StaticResource customer}">
<TextBox Margin="119,86,107,194"
x:Name="txtCustomerName" x:FieldModifier="protected"
Text="{Binding Path=Name,
ValidatesOnExceptions=True,
UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Add" HorizontalAlignment="Center" Margin="204,176,0,0" VerticalAlignment="Top" Width="74"/>
</Grid>
</Window>
3) In this case, the INotifyPropertyChanged is not required, since you are just interested in changing the value of the Source property (Name) by the interaction of the user in the TextBox, you are not modifying the Name property with other C# code. The INotifyPropertyChanged is implemented to notify the WPF data-binding system about changes in the data objetcs, so that WPF can update the data in user interface (update the Target when the Source is changed due to code procedures).
You didn't implement INotifyPropertyChanged.
Also keep your attention to IDataErrorInfo and INotifyDataErrorInfo.. which are using in case if you want to move validation logic out of setters.
Also need admit that in modern app better move validation logic in separate type. (see fluentValidation)
using System;
namespace TestValidation
{
public class Customer : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => this._name;
set
{
if(_name == value) return;
if (String.IsNullOrEmpty(value))
throw new ArgumentException("Customer name is mandatory.", nameof(Name));
_name = value;
OnPropertyChanged();
}
}
#region INotifyPropertyChanged
// TODO: Impelemnt interface INotifyPropertyChanged
// Create the OnPropertyChanged method to raise the event
// The calling member's name will be used as the parameter.
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
#endregion
}
}

Loading XAML to C# for Data Binding

Ok, we are trying out XAML for our GUI now (and learning as we go)...I have been able to do the data binding without a problem in XAML and C# independent of one another, but now comes the time I need to pass values back and forth and I'm a bit lost. When I compile and try to navigate to the page, it is throwing a XamlParseException: Specified class name doesn't match actual root instance type. Remove Class directive or provide an instance via XamlObjectWriterSettings.RootObjectInstance. Line 5 position 2.
Any help or a gentle shove in the right direction is greatly appreciated :)
Here's where I am:
namespace TheAirline.GraphicsModel.PageModel.PageFinancesModel
{
/// <summary>
/// Interaction logic for PageFinances.xaml
/// </summary>
public partial class PageFinances : Page
{
private Airline Airline;
public PageFinances(Airline airline)
{
InitializeComponent();
this.Language = XmlLanguage.GetLanguage(new CultureInfo(AppSettings.GetInstance().getLanguage().CultureInfo, true).IetfLanguageTag);
this.Airline = airline;
Page page = null;
//loading the XAML
using (FileStream fs = new FileStream("TheAirline\\GraphicsModel\\PageModel \\PageFinancesModel\\PageFinances.xaml", FileMode.Open, FileAccess.Read))
{
page = (Page)XamlReader.Load(fs);
}
//finding XAML element and trying to set the value to a variable
string airlineCash = GameObject.GetInstance().HumanAirline.Money.ToString();
TextBox cashValue = (TextBox)page.FindName("cashValue");
cashValue.DataContext = airlineCash;
}
}
}
And the first few lines of the XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:AirlineModel="clr-namespace:TheAirline.Model.AirlineModel"
mc:Ignorable="d"
x:Class="TheAirline.GraphicsModel.PageModel.PageFinancesModel.PageFinances"
xmlns:c="clr-namespace:TheAirline.GraphicsModel.Converters"
...>
</Page>
Bindings in XAML are resolved against the object that is assigned to the DataContext property of any given XAML element. The value of that property (as well as many other properties) Is Inherited in any given Visual Tree from parent elements to child elements.
for instance, given this class:
public namespace MyNamespace
{
public class ViewModel
{
public string Name {get;set;}
public bool IsActive {get;set;}
}
}
and this XAML:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyNamespace"
FontSize="20">
<Window.DataContext>
<local:ViewModel>
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding Path=Name}"/>
<CheckBox IsChecked="{Binding Path=IsActive}"/>
<StackPanel>
</Window>
All four objects defined in XAML, the Window, the StackPanel, the TextBox, and the CheckBox, will have a FontSize of 20, and the instance of the ViewModel class assigned to their DataContext property. Therefore all bindings (Except bindings with a specified ElementName, RelativeSource, or Source) will be resolved against that instance.
It would be exactly the same if the property was assigned in code instead of in XAML:
public MyWindow() //Window Constructor
{
InitializeComponent();
this.DataContext = new ViewModel(); //Note that keyword "this" is redundant, I just explicity put it there for clarity.
}
Because of this, there is no need to set the DataContext property to each element explicitly, as the framework is already taking care of that.
Also, notice that in XAML, most built-in Markup Extensions have a default constructor convention that allows you to abbreviate their usage. In the case of the Binding Markup Extension, the default constructor has the Path property, therefore this:
<TextBox Text="{Binding Path=Name}"/>
is exactly the same as this:
<TextBox Text="{Binding Name}"/>
Now, for property changes in the underlying DataContext to be automatically passed from the binding source (ViewModel) to the binding target (XAML-defined objects), the source object must implement the System.ComponentModel.INotifyPropertyChanged interface and raise the PropertyChanged event every time a property changes.
Therefore, in order to support Two-Way Binding, the example class should look like this:
public namespace MyNamespace
{
public class ViewModel: INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
_name = value;
NotifyPropertyChanged("Name");
}
}
private bool _isActive;
public bool IsActive
{
get
{
return _isActive;
}
set
{
_isActive = value;
NotifyPropertyChanged("IsActive");
}
}
}
public void NotifyPropertyChanged (string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName);
}
}
Notice that the ViewModel class has no dependency or direct reference to any of the XAML-defined objects, but still it contains the Values of the properties that will appear in the UI. This allows for a complete decoupling between UI and application logic/data known as the MVVM Pattern. I strongly suggest you research on that topic if you expect to be successful in programming in C# + XAML, because it is a radical mindshift when compared to other, traditional UI paradigms.
For example, something like this is not recommended in XAML-based applications:
if (myWindow.CheckBox1.IsChecked)
//Do Something
because that would mean that you're coupling the application logic and making it dependant on the state of UI elements, which is precisely what you need to avoid.
Notice that all the links and all the concepts referenced in this answer pertain to WPF, but are also applicable to Silverlight and WinRT. Since you did not specify which of the three XAML-based frameworks you're using, I posted the WPF ones, which is what I'm most familiar with.

Categories