C++ : Convertion operators
1: #include <iostream>2:3: class Test4: {5: public:6: // convertion from char const *7: Test( const char * _rhs )8: : _string( _rhs )9: {}10:11: // convertion to char const *12: operator char const * ()13: {14: return _string;15: }16:17: private:18: char const * _string;19: };20:21: int main()22: {23: Test instance("ala ma kota");24:25: std::cout << instance << std::endl;26:27: return 0;28: }
Test Live Writera Bety
Jakiś tam tekst.
Chapter 5. Serialization.
1. How to serialize an object.
In order to be able to serialize type it needs to be marked with [Serialized] attribute.
[Serializable]
class ObjectToBeSerialized
{
}
We can serialize such object like this:
1: using System;2: using System.IO;3: using System.Runtime.Serialization.Formatters.Binary;4:5: [Serializable]6: class ObjectToBeSerialized7: {8: }9:10: class Program11: {12: void Serialize()13: {14: ObjectToBeSerialized instance = new ObjectToBeSerialized();15:16: using (FileStream stream = File.Create( @"c:/output.bin"))17: {18: BinaryFormatter formatter = new BinaryFormatter();19: formatter.Serialize(stream, instance);20: }21: }22: }
2. How to deserialize object.
1:2: using (FileStream stream = File.Open(@"c:/output.bin", FileMode.Open))3: {4: BinaryFormatter formatter = new BinaryFormatter();5: ObjectToBeSerialized instance = (ObjectToBeSerialized )formatter.Deserialize(stream);6: }7:
3. How to handle values that are calculated / do not have to be serialized.
1: using System.Runtime.Serialization;2: using System;3:4: [Serializable]5: class ObjectToBeSerialized : IDeserializationCallback6: {7: private int m_value1;8:9: [NonSerialized]10: private int m_value2;11:12: public ObjectToBeSerialized( int _value1)13: {14: m_value1 = _value1;15: m_value2 = 10; // calculated value16: }17:18: public void OnDeserialization(object sender)19: {20: m_value2 = 10;21: }22: }23:
If we don’t want some fields to be serialized we mark them with [NonSerialized].
If we have some values that are not serialized but have to be initialized we can use IDeserializationCallback interface to handle that.
4. Serialization and version compatibility.
Styles in WPF.
Note on article’s inspiration: Article is based almost entirely on Windows Presentation Foundation Unleashed book which I recommend for all WPF learners.
Content:
1. What is style. Why do I need it?
2. Basic styling scenario.
3. How are elements connected with styles? – Named and typed styles.
4. I have typed style for Control type but it doesn’t work. Not a single subclass of Control has been changed. If I change it to named style everything is ok. What’s wrong? – Differences between named and typed style in target element’s type matching.
1. What is style. Why do I need it?
Style is not something you couldn’t live without. It’s yet another mechanism provided to make your life easier. If in your window you have several buttons and you want them all to have their text displayed in red we could set in each one it’s Foreground property’s value to red. However, since we all know the value of gathering such commonalities in one place we will use styles as a very handy tool in such cases. It’s more less like CSS. If you know CSS you get the idea.
2. Basic styling scenario.
We have a window layout containing several buttons.
1: <Window2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">4: <StackPanel Orientation="Vertical">5: <Button Content="First" />6: <Button Content="Second" />7: </StackPanel>8: </Window>
We want all buttons to have their text displayed in red so we define style that will do that for us.
1: <Window2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">4:5: <Window.Resources>6: <Style TargetType="{x:Type Button}">7: <Setter Property="Foreground" Value="Red" />8: </Style>9: </Window.Resources>10:11: ...12:13: </Window>
And here it is, our first style changing Foreground of all Buttons to red. Generally that’s it. You can add more setters to our style to customize more properties of all Button elements.
3. How are elements connected with styles? – Named and typed styles.
This one is important and at first a bit tricky. There are several ways to tell Button’s element instance that it should use our style.
- define so called named style and assign it to each Button’s instance explicitly
First button has it’s style set. Second one will stay unchanged by our style.
1: <Window.Resources>
2: <Style x:Key="buttonStyle">3: <Setter Property="Foreground" Value="Red" />
4: </Style>
5: </Window.Resources>
6:
7: <StackPanel Orientation="Vertical">8: <Button Content="First" Style="{StaticResource buttonStyle}"/>
9: <Button Content="Second" />10: </StackPanel>
11:
- define typed style for specific type
In this case all elements of type Button in window’s scope will have our style set implicitly.
You might wonder why our style defined in resources dictionary does not have it’s x:Key set. Well actually it has. It is set implicitly to the value of TargetType attribute.1: <Window.Resources>
2: <Style TargetType="{x:Type Button}">3: <Setter Property="Foreground" Value="Red" />
4: </Style>
5: </Window.Resources>
6:
7: <StackPanel Orientation="Vertical">8: <Button Content="First"/>9: <Button Content="Second" />10: </StackPanel>
11:
You can choose the one that suits your needs best. Both have their advantages.
4. I have typed style for Control type but it doesn’t work. Not a single subclass of Control has been changed. If I change it to named style everything is ok. What’s wrong? – Differences between named and typed style in target element’s type matching.
There is one very important, because hard to be figured out, difference between named and typed style. It is about what type they do match and what they don’t.
Let’s look at named style example:
1: <Window.Resources>2: <Style x:Key="controlTemplate">3: <Setter Property="Control.Foreground" Value="Red" />4: </Style>5: </Window.Resources>6:7: <StackPanel Orientation="Vertical">8: <Button Content="First" Style="{StaticResource controlTemplate}"/>9: <Label Content="Second" Style="{StaticResource controlTemplate}"/>10: </StackPanel>
In this style we set a Foreground property of Control element. It means that we can set this style to any element that is a subclass of Control and it will still work. This is a very convenient mechanism and it seems to be so natural that when we define typed style like the following we might wonder what’s wrong.
1: <Window.Resources>2: <Style TargetType="{x:Type Control}">3: <Setter Property="Control.Foreground" Value="Red" />4: </Style>5: </Window.Resources>6:7: <StackPanel Orientation="Vertical">8: <Button Content="First" />9: <Label Content="Second" />10: </StackPanel>11:
It seems to have the same meaning as previous named style but there is a fundamental difference in type matching. Typed style matches only elements of exactly the same types. In our case it would be a Control type. WPF Unleashed explains that it was done to avoid surprises. For example, they say, you can create style for ToggleButton but you don’t want it to be applied to CheckBoxes which is an subclass of a ToggleButton. For named style there is no such problem because you apply style explicitly.
How to display list of items – MVVM way.
What is that MVVM anyway?
The preferred way of connecting data with view in WPF applications seems to be MVVM pattern. MVVM stands for ModelViewViewModel. The whole idea behind it is to create a kind of a bridge between your data and logic at one side and view at the other. By using such bridge/buffer we avoid hardwiring our logic with view. It allows us to write application data and logic the way it should be written without taking shortcuts and making compromises just to be able to connect such code with a view. If written properly ViewModel can be unit tested which helps a lot in a world of GUI applications which are usually hard to test.
A little bit of practice.
Let’s start with a view model. What is a view model? For now let’s just think about view model as an object that provides view with whatever it requires in the form that is convenient for a view. Since view works with a few simple elements like properties containing data it can bind to and commands it can invoke these are two basic elements we will expose in out view model instance.
1: class MainWindowViewModel2: {3: public MainWindowViewModel()4: {5: People =6: new List<Person>()7: {8: new Person("Arek", 31),9: new Person("Magda", 26)10: };11: }12:13: public IList<Person> People { get; set; }14: }
Above we have our view model for main window. It provides view with a list of elements that we will bind to ListView’s control ItemsSource property.
For the sake of completeness of our view model example I have to say a few things about bindings here. Binding, according to MSDN, looks like this:
How our example works? Our binding target is ListView, binding source is MainWindowViewModel. Dependency property ItemsSource is bound in XAML to People property in view model. Our binding is in OneWay mode which means that data updates go only from People property to ItemsSource. Actually then don’t. They would if we implemented INotifyPropertyChanged interface in MainWindowViewModel. After that modification on view model looks like that:
(TODO: insert view model with updated implementation)
Now that we have our data we can move to a view implementation.
1: <Window2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4: xmlns:local="clr-namespace:SimpleList">5:6: <Window.Resources>7: <local:MainWindowViewModel x:Key="viewModel" />8: </Window.Resources>9:10: <ListView11: DataContext="{StaticResource viewModel}"12: ItemsSource="{Binding Path=People}" />13: </Window>
As you can see we create an instance of our view model in Windows.Resources section and than use it for setting DataContext of ListView control. First effect of our struggles looks like this.
It’s not exactly what we had in mind so what’s wrong? By default list view displays for each item text returned by it’s ToString() method.
One way to improve it would be like this.
1: <ListView2: DataContext="{StaticResource viewModel}"3: ItemsSource="{Binding Path=People}">4: <ListView.View>5: <GridView>6: <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>7: <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}"/>8: </GridView>9: </ListView.View>10: </ListView>
And the result:
Better, or maybe like this:
1: <ListView2: DataContext="{StaticResource viewModel}"3: ItemsSource="{Binding Path=People}">4: <ListView.ItemTemplate>5: <DataTemplate>6: <StackPanel Orientation="Horizontal">7: <TextBlock Text="Name:" Margin="10,0,5,0"/>8: <TextBlock FontWeight="Bold" Text="{Binding Name}"/>9: <TextBlock Text="Age:" Margin="10,0,5,0"/>10: <TextBlock FontWeight="Bold" Text="{Binding Age}"/>11: </StackPanel>12: </DataTemplate>13: </ListView.ItemTemplate>14: </ListView>
As you can see there is a lot of choices. Actually taking into consideration styles, templates, and ExpressionBlend we’ve got countless choices of how to show our data within a control.
How to create WPF application from scratch.
Our goal.
Our goal is to create most basic application in WPF. It is an application so we’ll create an Application instance. It is a WPF so we’ll add some UI element, let it be an empty Window instance.
Project and it’s basic “must have” settings.
First create new empty project. I like to start with an empty one in order to have everything under control. Later on it’s easy to create template out of our simple application and use it instead of doing everything again and again. When you’re done go to project properties and change application type to Windows Application.
Application definition.
Create Application.xaml file with following content.
1: <Application2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: StartupUri="MainWindow.xaml"4: />
After compiling that project compiler will complain, among other things, about lack of Main method. Visual Studio is able to generate Main method based on that file. In order to do that you have to change in Application.xaml’s properties it’s build action to ApplicationDefinition.
Line two works like a bunch of using statements. It imports a few core namespaces so that we can use core WPF types.
Line two instructs Application object to open resource defined in XAML. We can open resources of type Window of NavigationWindow.
Window definition.
In our case MainWindow.xaml contains a definition of new Window class which looks like this:
1: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"/>
What we have here is like above: import of core WPF namespaces and definition of new object of class Window.
And that’s it. We’ve got our first GUI application written using WPF library:) I won’t add anything to that example since the core idea was to show the most basic and simple application in WPF.
Why not even shorter?
It would be even more compact if we could treat Application as something similar to a ContentControl
1: <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">2: <Window />3: </Application>
but Application cannot have any content so we must stick with this two file solution.
How to display list of items.
In order to display a list of items we obviously need two things:
- a list of items
- some UI control prepared for the task of displaying lists
WPF is quite liberal about what can be our list of items. It can be a Collection or even IEnumerable. Of course it can work with more sophisticated types but more about it some other time.
When choosing a control we should know something about WPF Content Model idea. For our task best one will be a control implementing ItemsControl content model. When we’ve got our data and control the rest is easy. We just need to bind data to control and we do it like this:
Application instance like usually :
1: <Application2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: StartupUri="View/MainWindow.xaml"4: />
MainWindow that way:
1: <Window2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4: x:Class="SimpleList.MainWindow"5: >6: <ListBox ItemsSource="{Binding Path=Numbers}"/>7: </Window>
1: using System.Collections.Generic;2: using System.Windows;3:4: namespace SimpleList5: {6: public partial class MainWindow : Window7: {8: public MainWindow()9: {10: InitializeComponent();11:12: Numbers = new List<int>();13:14: Numbers.Add(1);15: Numbers.Add(2);16: Numbers.Add(3);17:18: this.DataContext = this;19: }20:21: public IList<int> Numbers { get; set; }22: }23: }
Important things we should remember are:
- Content Model idea
- DataContext dependency property provided by FrameworkContentElement
- the whole data binding mechanism
- the fact that we can define part of a class as partial class and e.g. set DataContext property that way
C# supplies us with a nice feature allowing to create such splitted class definition. It’s called partial class. Partial classes were added to allow for an easy integration with generated code. For example managed C++ does not support it (some say it is a good thing) which makes it much harder to use WPF with this language.
In our case it would look like this.
1: <Window2: xmlns="http://schemas.microsoft.com/netfx/2007/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4: x:Class="DatabaseGui.MainWindow"5: >6:7: </Window>8:
1: namespace Database2: {3: public partial class MainWindow : Window4: {5: public MainWindow()6: {7: InitializeComponent();8: }9: }10: }
From code’s perspective what is important is this partial keyword telling compiler that it is only a partial definition of MainWindow class. Compiler will look for all parts of that class and join them together.
For XAML’s perspective we can omit x:Class attribute. It has more less the same meaning as partial keyword used in code.
If we use x:Class in our XAML than, during XAML compilation new file MainWindow.g.cs is created. It contains automatically generated partial class for our MainWindow that does a lot of useful magic behind the scene. It contains a private field for any named element defined in XAML (that’s why you can use such elements so easy in your code-behind). It also contains InitializeComponent method that loads BAML resource, assigns fields to appropriate instances originally declared in XAML, and hook up events if any were specified in XAML. That is why it is so important to call InitializeComponent in MainWindow’s constructor.
O yeah!
No, to teraz zobaczymy. Zainstalowałem właśnie plugin Insert Code do Live Writera. Ciekawe jak to się będzie sprawować.
1: using System.Windows;
2: using System;
3:
4: namespace ListBoxApp
5: {
6: class Program : Application
7: {
8: [STAThread]
9: static void Main()
10: {
11: Program program = new Program();
12: program.Run( new MainWindow() );
13: }
14: }
15: }
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Hmm, jakiejś rewelacji nie widzę, ale bez przesady. W końcu chodzi o to żeby coś w końcu napisać na tym blogu, a nie w nieskończoność szukać idealnego syntax higlightera.
No to git. Sprawę uznajemy za załatwioną.
Test post.
This is just an example post to check how wordpress.com is able to handle c# source code. I’ve been trying to get it working for some time now but it looks like there is no way to do it easly. It’s a pity wordpress.com doesn’t have SyntaxHighlighter script from Alex Gorbatchev installed. It’d be so nice and easy. Anyway it’s not installed so we need to do it some other way.
Let’s find out what the output of http://dotnetslackers.com/articles/csharpformat.aspx looks like.
using System.Windows; using System; namespace ListBoxApp { class Program : Application { [STAThread] static void Main() { Program program = new Program(); program.Run( new MainWindow() ); } } }




