Best wpf questions in September 2010

Setting a custom property within a WPF/Silverlight page

16 votes

This sounds like it should be simple. I have a Page declared in XAML in the normal way (i.e. with "Add new item...") and it has a custom property. I'd like to set that property in the XAML associated with the page.

Trying to do this the same way that I'd set any other property doesn't work, for reasons I understand but don't know how to work round. Just so we've got something concrete to talk about, here's some (invalid) XAML. I've reduced everything down as much as possible - originally there were attributes such as the designer size, but I believe those are irrelevant to what I'm trying to do.

<Page x:Class="WpfSandbox.TestPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      MyProperty="MyPropertyValue">
</Page>

and the corresponding code-behind:

using System.Windows.Controls;

namespace WpfSandbox {
  public partial class TestPage : Page {
    public TestPage() {
      InitializeComponent();
    }

    public string MyProperty { get; set; }
  }
}

Error message:

Error 1 The property 'MyProperty' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. Line 4 Position 7.

Now I know why this is failing: the element is of type Page, and Page doesn't have a property called MyProperty. That's only declared in TestPage... which is specified by the x:Class attribute, but not by the element itself. As far as I'm aware, this configuration is required by the XAML processing model (i.e. the Visual Studio integration etc).

I suspect I could handle this with a dependency property, but that feels a little like overkill. I could also use an existing property (e.g. DataContext) and then copy the value into the custom property in code later, but that would be pretty ugly.

The above is a WPF example, but I suspect the same answers will apply in Silverlight. I'm interested in both - so if you post an answer which you know will work in one but not the other, I'd be grateful if you'd indicate that within the answer :)

I'm preparing to kick myself when someone posts an absolutely trivial solution...

You can work with normal property without Dependency property if you create a Base class for your Page.

 public class BaseWindow : Window
 {
   public string MyProperty { get; set; }
 }

<local:BaseWindow x:Class="BaseWindowSample.Window1" x:Name="winImp"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BaseWindowSample" 
    MyProperty="myproperty value"
    Title="Window1" Height="300" Width="300">

</local:BaseWindow>

And it works even though MyProperty is not a Dependency or Attached.

Microsoft Certification Advice : Silverlight path

9 votes

I apologize if this title is misleading. I already know that Microsoft isn't planning on releasing a Silverlight certification due to their quick development cycles (please correct me if I am wrong). I have started a new job that places a lot of emphasis on Microsoft Certifications, as of late I have been doing Microsoft Silverlight development in C#. I know Silverlight is more of a Web-Based platform compared to WPF but I was thinking maybe I should get my certification in .NET 4 C# Windows Development 70-511 (which covers WPF). I know the basics of C# and OOP principles, but also want to be relevant to Silverlight. I am assuming that there are enough similarities between Silverlight and WPF to do this. I realize I would put some extra study into WPF, but since the Microsoft Silverlight Certification doesn't exist do you think this would be a good alternative? Does the "Developer Community" place credence on a WPF certification if a Silverlight certification is being sought after?

Thanks for your help guys.

This just in: it looks like MS will be adding a Silverlight exam (70-506) starting January 2011. See: http://www.microsoft.com/learning/en/us/Exam.aspx?ID=70-506&Locale=en-us#tab1

Need comparison of MVVM / WPF / Silverlight Toolkits

8 votes

I'm looking for a good article that compares MVVM Light, Caliburn Micro, Prism, and any other Silverlight / WPF / WP7 frameworks out there. I've seen some good articles on them individually, but nothing that really pits them against one another. Any suggestions?

See this article http://www.japf.fr/2009/10/a-quick-tour-of-existing-mvvm-frameworks/

My recomandation if the app is not too big, better use MVVM Light, and after that deppending of your requirements, Prism(Last Version), nRoute, or Caliburn .

Can anyone provide a good "idiot's guide" to creating an installer in VS2008 (C#) Pro?

8 votes

I have Visual C# 2008 Professional and have developed the first half of a C# application (console mode) with the second half in progress now (GUI).

I'm looking for an easy path to creating an installer for it. What are the steps that need to be taken to produce a professional installer?

There's a similar question here regarding the Express edition but I have Pro, and I would like as much as possible to stick with just the standard VS stuff (if you think you can convince me that a third party installer creator is much better than a VS-only solution, give it a shot, by all means).

Keep in mind that I have no interest in upgrading to VS2010 yet, even if it's a hundred times easier to create an installer. That can come later, when the revenue starts rolling in :-)

Also be aware that the GUI component of this application is a totally separate executable from the console part. The console part is a simple "open file 1, do some work on it, write file 2" type and the GUI is a fairly standard "open file, do some stuff" beast so there's no tricky or wildly undocumented behaviour happening.

Basically, I'm looking for (at least) the following:

  • professional looking installer.
  • ability to specify where the application files go.
  • changes to the registry to allow double-clicks on my file extension to open the GUI app with the file as an argument.
  • needs to install everything required (my stuff, .Net if required, and so on).

Another option is using Inno Setup. It allows you to fully customize installations, where to stick files on the target machine, modify the registry, and all that jazz. If you're willing to spend a bit more time learning a bit about the scripting required to achieve the results you want, it's a very powerful tool. (fulfills all of your requirements and much more) And most importantly, it's free =)

I've been using Inno Setup for all of my larger .NET programs. When the installer runs, it checks to see if .NET is installed and if not, downloads and installs it. As well, I've modified registry and made associations with extensions like you mentioned. Including DLL's with the installer is simple as well - Inno will lump all of the required files into a single executable that takes care of everything.

Additionally, since Inno has been around since 1997, a number of editors have arisen that help make the scripting process a lot easier.

How to perform Single click checkbox selection in WPF DataGrid?

8 votes

I have a DataGrid with first column as text column and second column as CheckBox column. What I want is, if I click the check box. It should get checked.

But, it takes two click to get selected, for first click the cell is getting selected, for the second clicks the check box is getting checked. How to make the check box to get checked/unchecked with a single click.

Note:I'm using WPF 4.0

Edit: Columns in the DataGrid are AutoGenerated.

This is for 3.5sp1, I know - but it should work under 4.0: Vinsibal.

Using MAYA 3D Model in a .Net application

7 votes

If I want to render a 3D model created by Maya and do some animation with it in a .net application what should be my choice of platform - plain WPF or XNA?

XNA is an interesting platform, but I have noticed it having some performance issues when loading in models. I have not used WPF to do this, but XNA does also require installing of its framework, to run the application. I suggest you avoid it, for the hurdles you must jump to get what you want out of it. DirectX libraries are a good way to accomplish this, there are thousands of examples of this being used out there. Very Good,Good, Ok

You can also use a .X exporter for Maya to import your models. Something like this DirectX Maya Exporter

Static verification of bindings

7 votes

Or "how do you make sure all your bindings stay correct?"
(this is kinda lengthy, but bear with me, I tried to make it as short as I could)

Consider the following example:

    <TextBox Name="tb" />
    <TextBlock Text="{Binding Text.TheProp, ElementName=tb}" />

It is perfectly known at compile time that the binding is incorrect (i.e. the parser knows the type of element tb, and therefore, it knows the type of it's Text property, and therefore, it knows that TheProp doesn't exist).
Yet, this code will compile and run (although with a binding error message in debug output).

This behavior may come in very handy in some situations: no matter what exact type my data is, as long as it has appropriately named properties, I'm ok. Thus, we get sort of "declarative duck typing".

However, duck typing is not always a good thing.
Specifically, while using the MVVM pattern, I know (most of the time) the exact types of all my ViewModel objects. On the other hand, the models become more and more complex over time, which gets me worried about future refactoring: what if I decide to rename some properties, or, God forbid, put them in a separate aggregated object? What's going to happen with all my bindings then? Will I have to rake all XAML files by hand? And even without refactoring - what if I simply make a typo?

A similar problem is already solved in other places of XAML. If, for instance, you put an incorrect property name in Style/Setter/@Property, you get a compile time error.
TemplateBinding also provides such verification. Which is very handy.

So, ideally, I would love to see something like this:

ProductViewModel.cs:

    public class ProductViewModel
    {
        public Name { get; set; }
        public Price { get; set; }
    }

ProductView.XAML:

    <UserControl x:Class="Shopping.View.ProductView"
                 x:DataContextType="vm:ProductViewModel"
                 xmlns:vm="clr-namespace:Shopping.ViewModel"
                 ... >
        <TextBox Text="{Binding Name}" />  <!-- OK -->
        <TextBox Text="{Binding Price}" /> <!-- OK -->
        <TextBox Text="{Binding ABC}" />   <!-- Compile time error: there is no property ABC in ProductViewModel -->
    </UserControl>

ShoppingCart.XAML:

    <UserControl x:Class="Shopping.View.ShoppingCartView"
                 x:DataContextType="vm:ShoppingCartViewModel"
                 xmlns:vm="clr-namespace:Shopping.ViewModel"
                 ... >
        <ItemsControl ItemsSource="{Binding Products}"
                      ItemType="vm:ProductViewModel" >  <!-- Static check happens here 
                                                             ShoppingCartViewModel.Products must 
                                                             implement IEnumerable<ProductViewModel> -->
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="vm:ProductViewModel">
                    <view:ProductView /> <!-- DataContext is known to be of correct type
                                              because of DataTemplate.DataType property -->
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </UserControl>

But let's get back to reality. In reality, all that dreaming is just not going to happen in the near future.

However, I am sure I'm not the first person to have this problem.
So, finally, the question is: How do you make sure your bindings are correct? And that they stay that way?

How about static analysis of your Xaml performed as a post-build step?

As part of .Net 4, Microsoft released a new System.Xaml library to provide robust Xaml parsing and serialization support independent of WPF. They are now beginning to build all kinds of interesting things on top of it, some of which may help you out.

In the XamlToolkit, for example, you'll find the XamlDOM that enables you to do easy static analysis of Xaml files. And taking that a bit further, there's FxCop rules for XAML.

Of most interest is Rob Relyea's BindingFinder that has the explicit goal of type checking Bindings in Xaml. This requires that you have type hints in your Xaml, like the DataType attribute in a DataTemplate, or the the new d:DataContext attribute on your Views (which Blend uses to provide design-time data). It then uses the XamlDOM to check that everything matches up.

Why do RelayCommands typically use lazy initialization?

7 votes

When using Josh Smith's RelayCommand, most of the examples I've seen use lazy initialization such as:

public class ViewModel
{
    private ICommand myCommand;

    public ICommand MyCommand
    {
        get
        {
            if (myCommand == null)
            {
                myCommand = new RelayCommand(p => DoSomething() );
            }

            return myCommand;
        }
    }
    // ... stuff ...

}

Rather than creating the RelayCommand in the constructor, like this:

public class ViewModel
{
    public ViewModel()
    {
            MyCommand = new RelayCommand(p => DoSomething());
    }

    public ICommand MyCommand
    {
        get;
        private set;

    }

    // ... stuff ...
}

What's the benefit of using lazy initialization here? It will have to call the get property when setting up the binding, so I can't seen a reason to use this method over settings things up in the constructor.

Am I missing something here?

Actually, WPF and Silverlight will get the relay command just once per binding, so you don't really need to store a backing field at all:

public ICommand MyCommand
{
    get
    {
        return new RelayCommand(p => DoSomething());
    }
}

So while there's nothing wrong with creating it in the .ctor as you suggest, there's very little reason to.

Confused with wpf ComboBox DisplayMemberPath,SelectedValue and SelectedValuePath .

7 votes

I have always struggled with those comboBox properties

  1. DisplayMemberPath
  2. SelectedValue
  3. SelectedValuePath

I am building a master detail form .

  1. ComboBox filled with Customers
  2. User Selects a Customer in Combo
  3. All the textBoxes EG Fills correctly

The problem I am having I have made it work but I dont understand those properties and the differences. Is there a noddy example explaining what they do ? You might think is self explanatory.Well not to me.

Thanks for your input

I think we can understand this better with an example. See this class:

public class Employee
{
   public int Id;
   public string Name;
}

and the following xaml:

<ComboBox ItemsSource="{Binding Source={StaticResource Employees}}"
          DisplayMemberPath="Name"
          SelectedValuePath="Id"/>

DisplayMemberPath points to the Name property, so the value displayed in the ComboBox and the Employee entries contained in the drop down list, will be the Name property of the Employee object.

To understand the other two, you should first understand SelectedItem. SelectedItem will return the currently selected Employee object from the ComboBox. You can also assign SelectedItem with an Employee object to set the current selection in the ComboBox.

SelectedValuePath points to Id, which means you can get the Id of currently selected Employee by using SelectedValue. You can also set the currently selected Employee in the ComboBox by setting the SelectedValue to an Id (which we assume will be present in the Employees list).

Good or bad practise for Dialogs in wpf with MVVM?

7 votes

i lately had the problem of creating add and edit dialogs for my wpf app. all i want to do in my code was something like this. (I mostly use viewmodel first approach with mvvm)

ViewModel which calls a dialog window:

 var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", dialogwindowVM);

 ... do anything with the dialog result...

how does it works?

first i created a dialogservice

public interface IUIWindowDialogService
{
    bool? ShowDialog(string titel, object datacontext);
}

public class WpfUIWindowDialogService : IUIWindowDialogService
{
    public bool? ShowDialog(string titel, object datacontext)
    {
        var win = new WindowDialog();
        win.Title = titel;
        win.DataContext = datacontext;

        return win.ShowDialog();
    }

}

WindowDialog is a specail but simple window. i need it to hold my content:

<Window x:Class="WindowDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    Title="WindowDialog" 
    WindowStyle="SingleBorderWindow" 
    WindowStartupLocation="CenterOwner" SizeToContent="WidthAndHeight">
    <ContentPresenter x:Name="DialogPresenter" Content="{Binding .}">

    </ContentPresenter>
</Window>

a problem with dialogs in wpf is the dialogresult=true. this can only achieve in code. thats why i created an interface for my dialogviewmodel to implement.

public interface IDialogResultVMHelper
{
    event EventHandler DialogResultTrueEvent;
}

when ever my viewmodel think its time for dialogresult=true, then raise this event :)

for my WindowDialog this means register to this event:

public partial class WindowDialog : Window
{
    public WindowDialog()
    {
        InitializeComponent();
        this.DialogPresenter.DataContextChanged += DialogPresenterDataContextChanged;
    }

    private void DialogPresenterDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var d = e.NewValue as IDialogResultVMHelper;

        if(d == null)
            return;

        d.DialogResultTrueEvent += DialogResultTrueEvent;
    }

    private void DialogResultTrueEvent(object sender, EventArgs e)
    {
        this.DialogResult = true;
    }
}

now at least i have to create an datatemplate in my resource file(app.xaml or something)

<DataTemplate DataType="{x:Type DialogViewModel:EditOrNewAuswahlItemVM}" >
        <DialogView:EditOrNewAuswahlItem/>
</DataTemplate>

well thats all, i can now call dialogs from my viewmodels:

 var result = this.uiDialogService.ShowDialog("Dialogwindow title goes here", dialogwindowVM);

now my question, do you see any problems with this solution?

This is a good approach and I used similar ones in the past. Go for it!

One minor thing I'd definitely do is make the event receive a boolean for when you need to set "false" in the DialogResult.

event EventHandler<RequestCloseEventArgs> RequestCloseDialog;

and the EventArgs class:

public class RequestCloseEventArgs : EventArgs
{
    public RequestCloseEventArgs(bool dialogResult)
    {
        this.DialogResult = dialogResult;
    }

    public bool DialogResult { get; private set; }
}

What is a current analog of COM technology?

7 votes

COM technology seems a little outdated already, though still in use. But what approach is recommended now for implementing the same kind of interoperability when building a .NET app, specifically, in WPF?

I.e. what is a modern replacement of a COM object?

.NET was very much intended to be the replacement for COM. The project had many names while it was being worked on, but it started life as "COM+". This influence is still evident in many places. Many of the core source code files for the CLR start with the name "com", even though the CLR uses (almost) no COM at all. The Windows exception code for a managed exception is 0xE0434F4D. The last 3 byte values of the code is ASCII for "COM".

The assertion that WCF was a replacement is not accurate. It replaced .NET Remoting. COM has a very wide range, it is a generic interop tool, much like the CLR allows many languages to interoperate. One of its features was supporting interop between different processes and machines, perhaps the source of the statement. But that's just a part of it.

There are still lots of COM applications that have not been replaced by .NET. The best example is the Windows shell, Explorer.exe. Pretty hard to do something as simple as creating a context menu shell extension in C#. And until .NET 4.0 strongly discouraged.

Restrict Silverlight/WPF Behavior visibility

6 votes

In Silverlight (and probably WPF), when I define a System.Windows.Interactivity.Behavior<T> for e.g. an ItemsControl, like

public class SomeAwesomaticBehavior : Behavior<ItemsControl>
{
}

it will appear in Visual Studio's XAML editor (and probably in the Designer too) even for ordinary, non-Items-Controls and throw nasty runtime exceptions. This is contrary to Attached Properties which will appear only for intended types.

Is there a way to restrict that visibility? Some magic attribute maybe (although that would be a redundant declaration)?

If there is no way today, I hope there will be so in the future? Because it surely does confuse co-workers and designer folks when a lot of Behaviors pop up that don't have anything to do with the current object.

Update: I have filed uservoice items.

Silverlight: http://dotnet.uservoice.com/forums/4325-silverlight-feature-suggestions/suggestions/1224253-restrict-behavior-visibility?ref=title

WPF: http://dotnet.uservoice.com/forums/40583-wpf-feature-suggestions/suggestions/1224259-restrict-behavior-visibility?ref=title

@HeRz you are correct, there is no way to filter behaviors by their targeted type. Blend (and probably vs designer) use reflection to find all of the types you create which inherit from base type Behavior and displays them in the assets list.

Blend will prevent you from dragging a behavior or trigger onto an item which it is not intended. So that should help prevent their misuse.

I usually try to write behaviors as reusable pieces of code, not scoped to a specific case. They are simply tools with specific purposes.

What should I use in Prism- MEF or Unity?

6 votes

Found several good(related) questions here and here but all are nearly a year old.

I will like to know in the current context of Prism development what is better or at least scenario where each is better.

They are two approaches to solving some-what overlapping scenarios.

Unity shines when you are developing a modular application where users will be using a subset of the modules and modules are self-contained.

MEF shines when you have a lot of 3rd party developers creating plug-ins for your application - or several development teams publishing plugins.

We started out with Prism for core functionality and will be adding MEF for Widget-type functionality later - the idea being that border-line/customerspecific functionality will be delivered in MEF-plugins.

Both frameworks are really easy to get started with (MEF probably a bit 'simpler' from the get-go).

In my oppinion it really depends more on how your development strategy is structured rather than the application in question.

Is there a WPF message box?

6 votes

Is there a standard message box in WPF I should use, like WinForms System.Windows.MessageBox.Show()?

...or is it OK to use the WinForm message box?

The WPF equivalent would be the System.Windows.MessageBox. It has a quite similar interface, but uses other enumerations for parameters and return value.