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
You are accessing
SetRootPathin the constructor. At that point in time, XAML hasn’t yet had the chance to set your property, so it’s stillnull. Try to set the ItemsSource of your DocumentBrowser at a later time in the UserControl life cycle. A good choice would be the setter ofSetRootPath.(In fact, there are a few more “WPF-like” options for doing this:
Option A: Make
SetRootPatha 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
SetRootPathproperty, using a converter which applieslistDirectory.)PS: I’d call it
RootPath, notSetRootPath.