Tag Archives: Databinding

Databinding WPF treeview using recursion

15 Lug

Today I solved a very interesting problem using a TreeView and a HierarchicalDataTemplate. My final goal was to display an objects tree using a TreeView control as shown here below.

image

The result is not very nice but wait, I am a developer not a designer!
Ok, less chatter! Let’s look at the code that is much more interesting.
In this case the datasource is a tree composed by a set of Foo objects.
Here is the Foo class definition

public class Foo
{
    public Foo()
    {
        Children = new List<Foo>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Foo> Children { get; set; }
}

and here a dummy method that create a sample objects tree

public class Service
{
    private readonly Collection<Foo> fooList;

    public IEnumerable<Foo> FooList
    {
        get { return fooList; }
    }

    public Service()
    {
        fooList = new Collection<Foo> { new Foo { Id = 0, Name = "first" }, new Foo { Id = 99, Name = "makka" } };
        fooList[0].Children.Add(new Foo { Id = 1, Name = "second" });
        fooList[0].Children.Add(new Foo { Id = 2, Name = "third" });
        fooList[0].Children[0].Children.Add(new Foo { Id = 3, Name = "fourth" });
    }
}

Until here nothing special.
The interesting part is the XAML markup. As you can see using the power of HierarchicalDataTemplate with few lines of code we can create a recursive loop in order to populate the TreeView starting from a simple IEnumerable<Foo> object

<TreeView Name="viewsTreeView"  >
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Demo:Foo}" ItemsSource="{Binding Path=Children}">
            <TreeViewItem Header="{Binding Path=Name}"  />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

I hope this sample will save you some time!

When WPF Databinding change the way you write code

21 Mag

In these days I’m developing my first real production project with WPF and one of main different with Windows Form is Databinding. In WPF, databinding is very powerfull and sometimes allow you to write markup code that replace procedural code normaly used in Windows Form.

For example in this little piece of code I have written today use Databinding & Converter

image

in order to change StatusBar Visiblity when IsChecked property change on Checkbox

image image

The syntax is very compact and it’s very powerfull doing this things whit XAML markup but I’m wondering how to test this behaviour.

I thing in another post I will cover this topic.

 

Technorati Tag: ,,