开发者

How to pass data from parent control to descendants in WPF

开发者 https://www.devze.com 2023-03-14 15:00 出处:网络
I am writing a WPF app to display a list of employees in the company. My view model is basically a tree. Each company has a 开发者_开发问答list of employee and each employee has an address:

I am writing a WPF app to display a list of employees in the company. My view model is basically a tree. Each company has a 开发者_开发问答list of employee and each employee has an address:

Company
   Employee
      Address

The corresponding view for the Company object is CompanyViewControl which is derived from ItemsControl. In the control template, I bind Items to the list of employees and use a custom EmployeeViewControl in ItemsPresenter to display the content in each employee.

Everything is good.

Now I need to pass a special object from CompanyViewControl to EmployeeViewControl. How can this be done with the EmployeeViewControl defined/created in the template? To make things more complicated, the list of employees is loaded in a background thread. So when new employee is fetched, CompanyViewControl must pass the object to the new control which was just added.

I need to do this in such a way that I can create multiple views (ie, multiple instances of CompanyViewControl ) from a a single instance of the view models. Imagine the object is basically the parent control of the CompanyViewControl.


I am not sure I am understanding you correctly, yet the first question that comes to mind is 'why aren't you using a HierarchicalDataTemplate?'. This is generally the way I would personally template a tree structure as you describe.

As for passing information from the parent control to the child control, you can create a relativesource binding by type... this will also work through controls since in the logical tree, they would still be the parent.

ex.

<local:ParentControl Tag="Something..can be a binding">
    <local:ChildControl Tag="{Binding Tag, RelativeSource={RelativeSource AncestorType={x:Type local:ParentControl}, Mode=FindAncestor}}"/>
</ContentControl>

I hope this helps.


You could use the RelativeSource,e.g.

<Binding Path="SpecialCompanyInfo" RelativeSource="{RelativeSource TemplatedParent}">
0

精彩评论

暂无评论...
验证码 换一张
取 消