简体   繁体   English

具有不同内部datagrid ItemSource属性的WPF UserControls

[英]WPF UserControls with different inner datagrid ItemSource attribute

I've got three UserControls named UC. 我有三个名为UC的UserControls。 They are all the same except that the DataGrid they use within the layout needs a different DynamicResource for each. 除了在布局中使用的DataGrid各自需要不同的DynamicResource外,它们都相同。 Basically : 基本上:

<DataGrid ...
 ItemsSource="{DynamicResource Model1}"> <!-- I want to pass in this "Model1" string? -->

...
</DataGrid>

<DataGrid ...
 ItemsSource="{DynamicResource Model2}">

...
</DataGrid>

<DataGrid ...
 ItemsSource="{DynamicResource Model3}">

...
</DataGrid>

All of my user controls are created within a Window : 我所有的用户控件都在Window中创建:

<Window ...>

<my:UC/>
<my:UC/>
<my:UC/>

</Window>

As of right now my three UC's show the same data in the datagrid cause the dynamicresource is the same in all three, how do I pass a value to each usercontrol to change the dynamicresource within? 截至目前,我的三个UC在数据网格中显示的数据相同,这导致三个数据库中的dynamicresource都相同,如何将一个值传递给每个用户控件以更改其中的dynamicresource? Or how should this be handled I started doing WPF a day ago. 还是应该如何处理?我从一天前开始做WPF。

Thanks 谢谢

Create a dependency property in your user control which will hold the ItemsSource value ( DependencyProperty.Register ). 在用户控件中创建一个依赖项属性,该属性将保存ItemsSource值( DependencyProperty.Register )。 In your control bind DataGrid to this property. 在控件中,将DataGrid绑定到此属性。 Then set this property in your window from dynamic resources: 然后在窗口中通过动态资源设置此属性:

<Window ...>
    <my:UC DataGridItemsSource="{DynamicResource Model1}" />
    <my:UC DataGridItemsSource="{DynamicResource Model2}" />
    <my:UC DataGridItemsSource="{DynamicResource Model3}" />
</Window>

In order to bind DataGrid.ItemsSource in your control you can use either binding with ElementName=parentName or binding with RelativeSource=FindAncestor 为了在DataGrid.ItemsSource中绑定DataGrid.ItemsSource ,您可以使用ElementName=parentName绑定或RelativeSource=FindAncestor绑定

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

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