简体   繁体   English

C#WPF UserControl设置属性

[英]C# WPF UserControl set a property

Hi i have made my own UserControl, its a little windows explorer. 嗨,我做了我自己的UserControl,它是一个小的Windows资源管理器。

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" 和即时通讯用方法“ listDirectory”绑定我拥有的TreeView

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

when im calling it and i try to set the SetRootPath Property to a local path 即时通讯时,我尝试将SetRootPath属性设置为本地路径

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

the Variabel SetRootPath is everytime null and i get an Exception because nothing is assigned. Variabel SetRootPath每次都为null,并且由于未分配任何内容,因此出现异常。 So why is the Property never setted with the value that i assign? 那么,为什么属性永远不会设置为我分配的值呢?

regards 问候

The XAML parser first constructs the user control and then sets the SetRootPath property. XAML解析器首先构造用户控件,然后设置SetRootPath属性。 Therefore, SetRootPath is null in UserControl1's constructor. 因此,在UserControl1的构造函数中,SetRootPath为null。 You should move the line 你应该移动线

 this.DokumentBrowser.ItemsSource = listDirectory(SetRootPath); 

to a later point in the lifecycle of UserControl1. 到UserControl1生命周期的后期。 Or use a dependency property instead, and write an OnPropertyChanged handler. 或改为使用依赖项属性,并编写一个OnPropertyChanged处理程序。 (See http://msdn.microsoft.com/en-us/library/ms752914.aspx ). (请参阅http://msdn.microsoft.com/en-us/library/ms752914.aspx )。

You are accessing SetRootPath in the constructor. 您正在构造函数中访问SetRootPath At that point in time, XAML hasn't yet had the chance to set your property, so it's still null . 到那时,XAML还没有机会设置您的属性,因此它仍然为null Try to set the ItemsSource of your DocumentBrowser at a later time in the UserControl life cycle. 尝试在UserControl生命周期的稍后时间设置DocumentBrowser的ItemsSource。 A good choice would be the setter of SetRootPath . 一个不错的选择是SetRootPath的设置SetRootPath

(In fact, there are a few more "WPF-like" options for doing this: (实际上,还有更多类似“ WPF的”选项可以执行此操作:

Option A: Make SetRootPath a dependency property and change DocumentBrowser.ItemsSource during its PropertyChanged callback. 选项A:将SetRootPath为依赖项属性,并在其PropertyChanged回调期间更改DocumentBrowser.ItemsSource。

Option B: Like Option A, but don't handle PropertyChanged. 选项B:与选项A相似,但不处理PropertyChanged。 Instead, bind the DocumentBrowser's ItemsSource property to your SetRootPath property, using a converter which applies listDirectory .) 而是使用应用listDirectory的转换器将DocumentBrowser的ItemsSource属性绑定到SetRootPath属性。

PS: I'd call it RootPath , not SetRootPath . PS:我称其为RootPath ,而不是SetRootPath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM