WPF 4 Unleashed

Adam Nathan

Mentioned 17

Looks at the features and functions of Windows Presentation Foundation, covering such topics as XAML, creating an application object, content controls, pages and navigation, commands, data binding, and data templates.

More on Amazon.com

Mentioned in questions and answers.

I'am more a sysadmin and a webmaster than a developer, but sometime I develop, including C# principally using Winform (and optionally GTK+).

I've started few weeks ago a WPF project, and it seem really powerful, but at start I feel like a hen who found a knife! There is so many difference!

stackoverflow abounds about topic like that, and I've read carefully some who are similar like:

But, when somebody start with WPF from Winform, What are the differences to which he must pay attention?

[EDIT]

  • What about some advices/links for LINQ with WPF?
  • What about some advices/links WPF Navigation?

Thank you all, but all this is a bit diffuse, so I made a resources compilation and add some things by my own, please tell me what you think (or improve, I make it Community Wiki)

Strangely no one has talked about LINQ which seemed to be a central element of this technology.

Another thing that seems important to know given the time I lost, is not to use the WPF navigation system that doesn't seems to work properly from numerous sources I've read. So, it seem important to use a navigation framework, like Magellan.

And the routed event system seem to be an important point to look at in WPF, if somebody have some interesting resources about it, please add to this post.

RTFM

Software

Blog posts

Videos

The Code Project

Books:

Other Stack Overflow topics

WPF is completely different from other systems.

I have a few years of WinForms, Win32 and web programming experience, and I believe my web programming experience helped the most.

As for books, "Windows Presentation Foundation Unleashed" from Adam Nathan, Sams Publishing has helped me tremendously.

to getting started with WPF a design pattern Model View ViewModel (MVVM) would be important to know. also I would recommend Adam Nathan WPF4 book. I think it's great one!

Being new to WPF, and its apparently amazing ability to change, bind, enable, and otherwise manipulate. I'm trying to get a mental overview of what is happening and hope some can either confirm or correct my readings.

Before WPF, you have delegates and events. You could have a dozen controls all listening (via being registered to the event), so when the event fires, all other controls will be notified automatically and can act on however they were so coded. Such as...

From Code Behind, you would do something like

GotFocus += MyMethodToDoSomething;

Then, the signature method

private void MyMethodToDoSomething(object sender, RoutedEventArgs e)
{
  .. do whatever
}

Additionally, by using standard getter / setter, the setter can call its own methods in its own class to do something every time someone tries to get or set a value

private int someValue;
public int SomeValue
{
   get { this.DoSomeOtherThing();
         return someValue;
       }

   set { this.DoAnotherThing();
        someValue = value;
}

Now, there's dependency properties, and the one/two-way binding. I understand (I think) about one-way to simulate more of a read-only operation.

Anyhow, with two way binding, the dependencies automatically notify anyone "depending" on a change in either the source or target respectively, without an explicit check if something has subscribed to an event, the framework automatically handles the announcing of the change to the respective controls (target or source).

So, let me through this scenario out with an old Add/Edit Save/Cancel maintenance form. In an older framework, if someone clicked on an add or edit button, all the data entry fields would become "enabled" with either blank data for a new record, or editing existing data. At the same time, the add/edit buttons would become disabled, but the Save/Cancel buttons would now become enabled.

Likewise when finished via Save/Cancel, it would disable all the entry fields, save/cancel, and re-enable the Add/Edit buttons.

I don't quite understand how such this type of scenario would be handled under this dependency property scenario (yet), but am I close? I also understand you can bind to almost anything, including color schemes, show/hide, fonts, etc... But I'm taking small steps on trying to really grasp this stuff.

Thanks.

The poster has requested that I repost my comment as an answer. Happy to oblige :-)

Also I've found this book very helpful: http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195

My own experience with WPF involves going back between a bunch of different resources as I try to get my program to work. There's so much stuff in WPF it's really hard to keep it all in your head as you are learning it.

Possible Duplicate:
What is a dependency property?

hi guys, I have been browsing through the net to find the definition of a dependency prop, but cannot find the simplest def for this.Can anyone help me with an example? Thanks

Here is a quote from the WPF 4 Unleashed book:

WPF introduces a new type of property called a dependency property that is used throughout the platform to enable styling, automatic data binding, animation, and more. You might first meet this concept with skepticism, as it complicates the picture of .NET types having simple fields, properties, methods, and events. But when you understand the problems that dependency properties solve, you will likely accept them as a welcome addition.

A dependency property depends on multiple providers for determining its value at any point in time. These providers could be an animation continuously changing its value, a parent element whose property value propagates down to its children, and so on. Arguably the biggest feature of a dependency property is its built-in ability to provide change notification.

The motivation for adding such intelligence to properties is to enable rich functionality directly from declarative markup. The key to WPF’s declarative-friendly design is its heavy use of properties. Button, for example, has 111 public properties (98 of which are inherited from Control and its base classes)! Properties can be easily set in XAML (directly or by using a design tool) without any procedural code. But without the extra plumbing in dependency properties, it would be hard for the simple action of setting properties to get the desired results without the need to write additional code.

I want to learn “WPF using C#” properly.

I read basic concept of WPF using C# language. Since I know C++ and HTML It did not took too much time to read C# and XAML simple tutorial.

Now when I searched for the WPF tutorial, most of the sites give WPF features and some of the .net controls API and class usage.

But I want a book which will Guide a beginner in a proper way

Please any body suggest me a good book

Pro WPF in C# 2010: Windows Presentation Foundation in .NET 4
http://www.amazon.com/Pro-WPF-2010-Presentation-Foundation/dp/1430272058

Cover image

It is a very up-to-date book, and I learned WPF from it in 2008. It's for beginners, but covers everything, from "what is user32, what is gdi+ and what is directx" to "how to implement your own plugin system in a WPF app". The only missing part is the MVVM pattern explanation, thought it thoroughly deals with Data-Binding concepts.

Extracted from amazon:

What you'll learn

  • WPF basics: XAML, layout, control essentials, and data flow
  • WPF applications: Navigation, commands, localization, and
    deployment
  • Advanced controls: Custom controls, menus, toolbars, and trees
  • WPF documents: Text layout, printing, and document packaging
  • Graphics and multimedia: Drawing shapes, sound and video, animation, geometric transformations, and imaging
  • (note from me) I would also add Data-Binding as a strong 'plus' of this book

Who is this book for?

This book is designed for developers encountering WPF for the first time in their professional lives. A working knowledge of C# and the basic architecture of .NET is helpful to follow the examples easily, but all concepts will be explained from the ground up.

WPF4 Unleashed from Adam Nathan. the best wpf book i know.

WPF4 Unleashed Link

I've searched my little heart out and its entirely possible that I'm missing something critical and obvious.

I have a BitArray and a series of checkboxes that are bound to elements in the array, like so:

<CheckBox IsChecked="{Binding Permissions[0]}" />
<CheckBox IsChecked="{Binding Permissions[1]}" />
...
<CheckBox IsChecked="{Binding Permissions[5]}" />

They get their values from that property correctly, but changing the checkboxes doesn't seem to trigger that property's setter.

I tried a really simple example with a single TextBox bound to an element of a string array.

class TestArray
{
    private string[] _nameArray = new string[3];

    public TestArray()
    {
        _nameArray[1] = "test name";
    }

    public string[] NameArray
    {
        get { return _nameArray; }
        set { _nameArray = value; }
    }
}

Here's the UI element:

<TextBox Text="{Binding NameArray[1], UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

Again, this TextBox gets the name from the binding just fine, but doesn't hit the setter if I change it.

This could totally be a bonehead question and may stem from a serious lack of understanding so thanks for your patience!

The thing that is missing is the notification that the value has changed. When you bind to standard .NET properties (so-called CLR Properties), you need to trigger an additional event to inform the control about the value change. Have a look at this SO Question. In addition MSDN might be helpful.

I can also recommend to read some of WPF basic concepts first. Books like WPF in Action (slightly outdated) or WPF Unleashed might help.

For the past 5 months or so, I've spent time learning C# using Andrew Troelsen's book and getting familiar with stuff in the .NET 4 stack... bits of ADO.NET, EF4 and a pinch of WCF to taste.

I'm really interested in graphics development (not for games though), which is why I chose to go the .NET route when I decided choose from either Java or .NET to learn... since I heard about WPF and saw some sexy screenshots and all. I'm even almost done with the 4 WPF chapters in Troelsen's book.

Now, all of a sudden I saw some post on a forum about how "WPF was dead" in the face of something called Silverlight. I searched more and saw all the confusion going on at present... even stuff like "Silverlight is dead too!" wrt HTML5.

From what I gather, we are in a delicate period of time that will eventually decide which technology will stabilize, right?

Even so, as someone new moving into UI & graphics development via .NET, I wish I could get some guidance from people more experienced people. Maybe I'm reading too much? Maybe I have missed some pieces of information? Maybe a path exists that minimizes tears of blood?

In any case, here is a sample vomiting of my thoughts on which I'd appreciate some clarification or assurance or spanking:

  • My present interest lies in desktop development. But on graduating from college, I wish to market myself as a .NET developer. The industry seems to be drooling for web stuff. Can Silverlight do both equally well? (I see on searches that SL works "out of browser").

  • I have two fair-sized hobby projects planned that will have hawt UIs with lots of drag n drop, sliding animations etc. These are intended to be desktop apps that will use reflection, database stuff using EF4, networking over LAN, reading-writing of files... does this affect which graphics technology can be used?

  • At some later point, if I become interested in doing a bit of 3D stuff in .NET, will that affect which technologies can be used?

  • Or what if I look up to the heavens, stick out my middle finger, and do something crazy like go learn HTML5 even though my knowledge of it can be encapsulated in 2 sentences?

Sorry I seem confused so much, I just want to know if there's a path of least resistance that a newcomer to graphics-technology-adoption can take at this point in the graphics world.

WPF and Silverlight are definitely alive and well. Also, don't let people fool you into thinking it has a "steep learning curve" (which is a common myth.) WPF isn't a walk in the park, granted, but it is also not the hardest thing to learn.

I recommend the book "WPF 4 Unleashed" by Adam Nathan. http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195 It will teach you everything you need to get started with WPF (and Siverlight, which is WPF-based.)

I am going to make my project from Visual C#(Visual Studio 2010).. So i want some nice interfaces for my projects..

So that i have heard that Microsoft Expression Studio got the ability to make those nice interfaces.. Now Microsoft Expression Studio software is installed with me..

I Have 2 Questions..

1) My first question is can i create normal windows forms(Not WPF forms) with this scenario using Microsoft Expression Studio...?

2)Though yes or no i have prior experience of creating Windows forms from Visual Studio... can you give me some Tutorial Links(Video/Others) to this scenario...

Its better if its possible in normal forms without using WPF because i dont have any knowlage about WPF... And this is not a Web application this is Stand alone application..

Expression Blend is for WPF only.

You can try third party apps like Tekerik's VisualStyleBuilder for Winforms.

However, if this is a new application you may want to invest some time and learn WPF. There are some great Tutorials and Books on WPF out there.

Plus learning XAML will be helpful in building Windows 8 Metro apps.

I am a C# programmar and now I want to learn WPF and silverlight.

Plz suggest me how should I proceed(from the very beginning) ?

and also some resources and books on it.

I learned Silverlight from this book: http://www.amazon.com/Pro-Silverlight-4-Matthew-MacDonald/dp/1430229799 and thought it was perfect.

For WPF you can use WPF Unleashed. It starts with the basic stuff and you'll end up learning everything you need to know. It's also quite useful just for references.

I have a WritableBitmap and I want to get its dimensions. Because the object is owned by another thread, we have to go through the Dispatcher. I've tried this:

int targetPixelWidth = 0;
int targetPixelHeight = 0;

writeableBitmap.Dispatcher.Invoke(new Action(() =>
{
    targetPixelWidth = writeableBitmap.PixelWidth;
    targetPixelHeight = writeableBitmap.PixelHeight;
}));

// Do something with targetPixelWidth and targetPixelHeight

However, this sometimes fails: the values often remained 0, even though the real values are different.

Thinking it might be a threading issue, I changed the code as follows:

var bitmapInfo = (Tuple<int, int>)writeableBitmap.Dispatcher.Invoke(new Func<Tuple<int, int>>(
   () => Tuple.Create(writeableBitmap.PixelWidth, writeableBitmap.PixelHeight)
));

Debug.Assert(bitmapInfo != null, "Obviously, this should pass.");

targetPixelWidth = bitmapInfo.Item1;
targetPixelHeight = bitmapInfo.Item2;

// Do something with targetPixelWidth and targetPixelHeight

But now, bitmapInfo is sometimes null. Which is strange, because (according to the documentation) Invoke should only return null when the delegate has no return value, which it obviously does in this case. I've even Debug.Asserted the return value of Tuple.Create, and it was never null.

What am I missing here? What causes this race condition, and what can I do about it?

This works, although I don't know why:

ManualResetEventSlim mre = new ManualResetEventSlim(false);

int targetPixelWidth = 0;
int targetPixelHeight = 0;

writeableBitmap.Dispatcher.Invoke(new Action(() =>
{
    try {
        targetPixelWidth = writeableBitmap.PixelWidth;
        targetPixelHeight = writeableBitmap.PixelHeight;
    }
    finally {
        mre.Set();
    }
}));

mre.Wait();
// Do something with targetPixelWidth and targetPixelHeight

Somebody (who posted an answer to this question but later removed it), suggested that Invoke is synchronous on the GUI thread, not on the thread that calls Invoke. If that's true, that would explain why this works. However, the documentation, the books [1, 2] and little toy programs attempting to reproduce this problem, all suggest that this is not the case; Invoke should be synchronous on the calling thread.

I haven't been able to come up with a real explanation; if someone has one, I'm all ears :).

EDIT Replaced my original, somewhat rambling answer with something more coherent.

Windows Forms is pretty old now, and has been superseded by WPF. I've seen a lot of material regarding databinding WPF layouts, using the MVVM pattern for the applications and some cool animations to boot.

I think it's time for me to abandon the Winforms ship and start using WPF. Once I finish this last freelance project I'll start using WPF exclusively for my Windows Clients.

I have the privilege of having customers with newer machines, so running WPF on their machine won't be a problem. :)

Trying to grab the entirety of WPF is extremely daunting and I feel that if I just dive right in I might keep doing things the Winforms way when in fact WPF has a newer, more succinct way of doing things.

Where do you recommend I start? What are some things you wish you knew before using WPF for production? What book would you recommend that teaches you about WPF (has to be new! nothing from 2007)?

I've just done the exact same thing. I am in the process of moving some apps to WPF. I've decided not to bite off MVVM just yet, or any VM. I'm just trying to learn the basics of WPF. I have found SO, other internet sites and this book very helpful.

BTW, I'm finding it's much easier than I thought. Takes some getting used to, but I'm already hooked (XAML is very cool). I'm convinced the best to learn is to simply jump in and start doing it.

I am reading WPF 4 Unleashed and I am obviously new to WPF (and C# & .NET in general)

In the book, found the following snipped of code:

<StackPanel TextElement.FontSize=”30” TextElement.FontStyle=”Italic”
Orientation=”Horizontal” HorizontalAlignment=”Center”>
<Button MinWidth=”75” Margin=”10”>Help</Button>
<Button MinWidth=”75” Margin=”10”>OK</Button>
</StackPanel>

TextElement.FontSize is an attached property. I don't understand why is it attached property ? (Though, I do understand the concept of dependency property)

In Attached Properties Overview on MS site, there is another snipped of code.

<DockPanel>
  <CheckBox DockPanel.Dock="Top">Hello</CheckBox>
</DockPanel>

In this case, it makes sense as to why DockPanel.Dock is an attached property - DockPanel class contains dependency property DockProperty.

If you're new to C#, I strongly suggest you start by doing some Hello, World! type of stuff in console applications before trying to get into complex WPF GUI stuff.

WPF is a complex framework not really suitable for the unexperienced. You must have a strong background in C# and OOP in general in order to learn MVVM, which is what you must learn in order to use WPF properly.

That said, StackPanel does not have a FontSize property because it's a Panel and not a Control, which is where the FontXXX properties are defined. That's why you can optionally define the TextElement.FontSize Attached Property, which are child controls will inherit due to Dependency Property Value Inheritance in the Visual Tree.

As an aside, that book was in a former coworker's desk, so I grabbed it and rapidly browsed thru it. I didn't find a single mention to MVVM, which at this point I consider a fundamental part of the WPF learning curve.

I have learned about programming for 3 years from Assembly to BASIC to C and WPF, but I wonder that inside the reference book, did't much help me in creating a simple/ complex , a complete system. I never touch C# before and its totally different between C# and WPF, many source code provide a separate program without link to database , and when i tried to connected to database, my application is malfunction. I try to find a complete sample LOB app,but when i figure out why i download from Codeproject is very complicated ....and its MVVM ... a more complicated than what i think. I need a professional give me an advice ...I am a graduated diploma student and a WPF self learner.

i think u should read good books about CLR/C# (such as this) and more specifically about WPF (i recommend either WPF 4 Unleashed or Pro WPF in C# 2010)

also, u can find nice code samples at WPF samples

And ,finally, u should necessarily code ur own programs: more code - more experience

I have recently been reading Adam Nathan's excellent WPF 4 Unleashed book. However, my goal is to be able to develop WinRT applications ( using C# ) and I have already noticed some differences between WinRT ( WPF 4.5? ) and WPF 4 which is discussed in the book, such as WinRT doesn't have a DockPanel or Label controls and there is a some code in App.xaml.cs that basic WPF4 applications doesn't have.

So, I am just wondering if there are some other major differences between WinRT and normal WPF4 applications and if I should find a tutorial or a book which is about WinRT specifically ( by the way, feel free to suggest one ).

I'm really excited to learn system programming on the windows platform. I just started reading "Programming Windows Fifth Edition" and I noticed that it's mostly GUI-Oriented.

Excuse me for a maybe-dumb question, but isn't all this can be used in an IDE instead of writing dozens of lines of code to write a windows form or a drop-down menu ?

Is there a way to avoid all this and directly tackle system programming ?

http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195/ref=sr_1_1?ie=UTF8&qid=1311145232&sr=8-1

The whole unleashed series are very good.

WPF is one of the newest ways to do windows software development.

Another up and coming way is HTML5 and javascript. See the next version of windows. I don't remember the codename.

public ImageSource imagesource
{
   get
   {
      string constring=@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource='C:\picdata.mdb'";
      OleDbConnection cn = new OleDbConnection(constring);

      cn.Open();
      OleDbDataAdapter da = new OleDbDataAdapter("select * from picdata", cn);
      DataSet ds = new DataSet();
      da.Fill(ds);
      cn.Close();

      var Img = new BitmapImage();
      Img.BeginInit();
      byte[] content = (byte[])ds.Tables[0].Rows[0].ItemArray[0];
      MemoryStream stream = new MemoryStream(content);
      Img.StreamSource = stream;
      Img.EndInit();

      return Img;
   }
}

XAML FILE

<my:DataGrid AutoGenerateColumns="True" Margin="308,12,255,50" Name="dataGrid3"  >
    <my:DataGridTemplateColumn Header="Image" >
        <my:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Image Name="display" Margin="201,29,0,0" Stretch="Fill" Source="{Binding imageSource}">      </Image> 
            </DataTemplate>
        </my:DataGridTemplateColumn.CellTemplate>
    </my:DataGridTemplateColumn>
</my:DataGrid>

The property imagesource is not invoked. Do you have any suggestions?
I have successfully done the conversion and binding using C# and DataGridView but I am unable to figure it out using WPF. I am completely new to WPF so any help would be greatly appreciated.
How else could I successfully bind the access database containing pictures (conversion required) to a DataGrid? Why isn't the imagesource property being executed?

I strongly suggest you to read some tutorials on WPF. It looks like you need some WPF basic knowledge. There are so many reasons that your code will not work...

I recommend this one for the WPF DataGrid and WPF 4 Unleashed (Amazon.com) as a good reading about WPF in general.

  • Your ViewModel needs to implement the INotifyChanged interface so that the UI will know where and when to look for changed properties.

  • In the setter - not the getter - you need to call a PropertyChangedEvent that notifies the UI to react to it.

  • Too much code for just a getter. Your database connection will be opened each time you call the property getter. A getter should just return a simple value without accessing expensive resources. (Hava a look at Microsoft's Rico Marian's blog about this topic here.)

So, in Office 2013, the applications have animations such as a "smooth typing" animation, along with things such as the email list in Outlook smoothly moving emails rather than just deleting one out of the list, or having the Backstage View smoothly slide out from the side of the screen. I'd like to add some similar animations to my applications in the future.

I have some ideas in my head about how to animate these, but before I dive into a lot of custom work I was wondering if anyone knew of a framework or something that added support for this type of thing easily.

Also, I have previously done all my work in WinForms- in your opinion, would it be better for me to take this as an opportunity to start learning WPF? I've heard a few times it's more "animation friendly".

Thanks!

Take this as an opportunity to learn WPF. WPF is great with animations and it uses hardware acceleration to increase performance (provided you're not running on WinXP or anything before that).

You can also look into acquiring Microsoft Blend which will help you create animations in your WPF applications.

I would also suggest this book. I haven't seen a better resource than this.