Tag Archive: wpf

Learning MVVM from the ground up for building real-world software

My two MVVM video series` on YouTube have become very popular, and I have every intention of continuing getting more information out there on MVVM through my Enterprise series. If you haven’t had a chance to check out the videos, here is the full list below.

MVVM Session 1 – http://youtu.be/EpGvqVtSYjs
MVVM Session 2 – http://youtu.be/Dzv8CtUCchY
MVVM Session 3 – http://youtu.be/OOHDie8BdGI

Enterprise MVVM Session 1 – http://youtu.be/lool8Ut58Xw
Enterprise MVVM Session 2 – http://youtu.be/CpVNMmefvDo
Enterprise MVVM Session 3 – http://youtu.be/RbfqNOSyYok
Enterprise MVVM Session 4 – http://youtu.be/7SwgqLJCLI8

MVVM Questions and Answers – http://youtu.be/j8Fke2cUTTc

I want to thank everyone who has followed my series and provided feedback. It has emboldened me to ensure I provide quality content and continue the effort of producing videos. MVVM in of itself is a simple concept, but a lot of questions stem from people trying to build real-world software, and finding material for that can be difficult. From the basic stock ticker demos to simple CRUD applications and Msdn articles, none of these really actually demonstrate a full stack MVVM application using dependency injection, service locater’s, messengers, unit testing, mocking; basically the full stack. This is what I intend to do through the enterprise MVVM series. Maybe I will write a book at some point. Who knows. Right now though, I’m enjoying producing the video content.

I also just ordered new sound equipement, the RODE PodCaster microphone, as my Blue Yeti one sort of, well, fizzled out I guess. Bummer, but looking forward to the new one already. Anyhoot, check out the videos if you haven’t already. And again, thank you to my followers!!

Enterprise MVVM in WPF: Adding Data and Business Layers using Entity Framework

Second video in the Enterprise MVVM in WPF series where I demonstrate the practice of adding a data layer and business layer using Entity Framework and test driven development (TDD). Learn how to make a unit of work business context that you can use to encapsulate your business rules and logic, but still be able to go a layer down to entity framework.

Grab the source code here, and the slide deck here. Don’t forget to like and subscribe if these videos helped you. 🙂

Series:
Part 1: https://www.youtube.com/watch?v=lool8Ut58Xw&hd=1
Part 2 (this video): https://www.youtube.com/watch?v=CpVNMmefvDo&hd=1

Enterprise MVVM in WPF: ViewModel Validation using Data Annotations

I finally had some time off from my busy work life to produce a few WPF MVVM videos on my YouTube channel. It is a bit of a relief to finally get some content up for you guys again. Prior, I believe the last video I had done was a bit over a year ago. The video is the irst video in a new series on what I consider to be enterprise MVVM development for WPF. We will begin covering practical application development scenarios that you will encounter in the real-world, and focus on building high quality, low maintenance, enterprise solutions.

Video:

You can grab the demo code here, and the slide deck here. Like and Subscribe for more videos!

Series:
Part 1 (this video): https://www.youtube.com/watch?v=lool8Ut58Xw&hd=1
Part 2 :https://www.youtube.com/watch?v=CpVNMmefvDo&hd=1

Video Notes:
– I apologize for the low audio, the new microphone (Blue Yeti) picks up pretty much all background noise, and my desktop PC is very loud. I will be looking into ways to resolve this, and if anyone has recommendations please let me know.
– When I originally created the projects I had Visual Studio set to .NET 4. If you are using Visual Studio 2012 or 2013, make sure you set your projects to target .NET 4.5 or .NET 4.5.1.
– There are two parts where the audio may seem like it was edited, and this was true. Sometimes noise from other people makes it into a video and I do my best to edit it out without ruining the video content.
– The downloadable source code will be much cleaner than what was demonstrated in the video. I will be focusing more on the approaches in my videos, and cleanup can always come later.
– The downloadable source code will also contain many more unit tests, including some unit tests for the view models that we were not able to do in the screencast originally.

Thank you everyone for all your support! I have been listening to the questions and feedback in the comments, and paying attention so that I will be focusing my attention on the questions and topics you guys are asking for.

IValueConverter Interface (System.Windows.Data.IValueConverter)

Probably the most common question I get from people new to WPF is how to bind the Visibility of a control based on a System.Boolean value. WPF provides IValueConverter in System.Windows.Data specifically for converting one type to another and back when binding. Let’s setup a very simple example.

/// <summary>
/// ViewModel for MainWindow
/// Assigned to MainWindow.DataContext in its class constructor
/// </summary>
internal class MainWindowDataContext : INotifyPropertyChanged
{
    private bool _visible;

    public bool Visible {
        get {
            return _visible;
        }
        set {
            _visible = value;

            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null) {
                handler(this, new PropertyChangedEventArgs("Visible"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Visibility="{Binding Visible}" />
    </Grid>
</Window>

You should already know that line 7 doesn’t work. There isn’t a conversion from System.Boolean to System.Windows.Visibility. This is where IValueConverter comes in, so we will make a new class that implements the interface and call it BoolToVisibilityConverter.

internal class BoolToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is bool)) {
            throw new System.ArgumentException("value is not of type System.Boolean", "value");
        }
        return (bool)value ? Visibility.Visible : Visibility.Hidden;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (!(value is Visibility)) {
            throw new System.ArgumentException("value is not of type System.Windows.Visibility", "value");
        }
        switch ((Visibility)value) {
            case Visibility.Visible:
                return true;
            default:
                return false;
        }
    }
}

The implementation is simple. When the binding gets the value from MainWindow.DataContext (eg. MainWindowDataContext.Visible) it is passed to the value parameter of object Convert. Then it’s up to the convert method to return the appropriate value based on the parameter. In this case, we do a simple check to make sure the parameter is in fact a System.Boolean value, and if it is we return the appropriate Visibility enumeration value. Obviously, ConvertBack does exactly the opposite when the value of the binding is set, and is propagated down to the data context. It takes a Visibility value and converts it to a System.Boolean value, which is assigned to MainWindowDataContext.Visible.

Now we need to update our Xaml to use the converter. This is done by including it as a resource and specifying the Converter attribute on the binding.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverterResourceKey"/>
        </Grid.Resources>
        <Button Visibility="{Binding Visible, Converter={StaticResource BoolToVisibilityConverterResourceKey}}" />
    </Grid>
</Window>

You can implement IValueConverter any time you need to convert one type to another and back in a binding.

How Auto width Grid columns work with column spanning.

A friend of mine was wondering if he had encountered a bug in WPF today. What he was trying to do is have a Grid with four columns, each with a width of Auto, and have a TextBox fill the entire width of his Grid. Here was his Xaml.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="4" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>

What he wants is for his TextBox to take up the remaining width in the Grid. The way Auto works for a GridColumn‘s width, is that it sizes itself to the maximum width of its content. So in this case, the width of each column is that of the width of each button. Now because there are only four columns defined in the Grid, the TextBox can only span a maximum of four columns. The remainder of the Grid is undefined space that fills the Window, because the default behavior of a Grid is to fill its parent container.

So how do we get the TextBox to fill the undefined space? You define it. Add a fifth column with a * width, which means it will fill the remainder of the Grid space, and then we can set the TextBox to span all five columns, instead of the first four.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Grid.ColumnSpan="5" Grid.Row="0"
                Margin="5,6"
                HorizontalAlignment="Stretch" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" />

    <Button Grid.Row="1" Grid.Column="0" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="1" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="2" Margin="3" Content="Hello" />
    <Button Grid.Row="1" Grid.Column="3" Margin="3" Content="Hello" />
</Grid>