views:

25

answers:

2

Hi i have made my own UserControl, its a little windows explorer.

i defined a Property in the Control that sets the Path where the Explorer should start from listing the Directory:

 public string SetRootPath
    {
        get { return rootPath; }
        set { rootPath = value; }
    }

and im binding the TreeView that i have with a method "listDirectory"

 public UserControl1()
        {
            InitializeComponent();
            this.DokumentBrowser.ItemsSource = listDirectory(SetRootPath);
        }

when im calling it and i try to set the SetRootPath Property to a local path

<mycontrol:UserControl1 SetRootPath="c:\\temp" />

the Variabel SetRootPath is everytime null and i get an Exception because nothing is assigned. So why is the Property never setted with the value that i assign?

regards

+1  A: 

You are accessing SetRootPath in the constructor. At that point in time, XAML hasn't yet had the chance to set your property, so it's still null. Try to set the ItemsSource of your DocumentBrowser at a later time in the UserControl life cycle. A good choice would be the setter of SetRootPath.

(In fact, there are a few more "WPF-like" options for doing this:

Option A: Make SetRootPath a dependency property and change DocumentBrowser.ItemsSource during its PropertyChanged callback.

Option B: Like Option A, but don't handle PropertyChanged. Instead, bind the DocumentBrowser's ItemsSource property to your SetRootPath property, using a converter which applies listDirectory.)

PS: I'd call it RootPath, not SetRootPath.

Heinzi
Thanks! put it to a later state and it worked fine. that with the dependency properties i should read something about that. im really new with this stuff and get every day tons of new impressions.
Mark
+1  A: 

The XAML parser first constructs the user control and then sets the SetRootPath property. Therefore, SetRootPath is null in UserControl1's constructor. You should move the line

 this.DokumentBrowser.ItemsSource = listDirectory(SetRootPath); 

to a later point in the lifecycle of UserControl1. Or use a dependency property instead, and write an OnPropertyChanged handler. (See http://msdn.microsoft.com/en-us/library/ms752914.aspx ).

fmunkert
+1 for the MSDN link.
Heinzi