如何从 wpf 中的另一个数据模板访问数据? [英] How to access data from another datatemplate in wpf?
问题描述
我有 2 个数据模板.一个包含一个网格,第二个包含一个按钮.我需要将按钮的命令参数作为选定的网格项发送.
I have 2 Datatemplates. One contain a grid , second one contain a button. I need to send command parameters of button as selected grid items.
我该怎么做?
<ObjectDataProvider x:Key="Datas" ObjectType="{x:Type ViewModel:UserControlViewModel}"></ObjectDataProvider>
<DataTemplate x:Key="SourceGrid">
<WPFToolKit:DataGrid x:Name="SourceDataGrid" ItemsSource="{Binding Source={StaticResource Datas},Path=SourceGridData}" CanUserSortColumns="True" GridLinesVisibility="None" IsSynchronizedWithCurrentItem="True" SelectionUnit="FullRow"></WPFToolKit:DataGrid>
</DataTemplate>
<DataTemplate x:Key="AddRemoveDataTemplate">
<StackPanel>
<Button Name="Add" Content="Add">
<Button.Command>
<Binding Source="{StaticResource Datas}" Path="AddCommand">
</Binding>
</Button.Command>
<Binding ElementName="SourceDataGrid" Path="SelectedItem"></Binding>
</Button.CommandParameter>
</Button>
<StackPanel>
</DataTemplate>
推荐答案
您可以尝试使用 Binding
并将 RelativeSource
属性设置为 FindAncestor
模式并寻找 DataGrid
对象.但是,我不确定它是否适用于您的场景,因为我不知道这些 DataTemplate
是如何相互关联的.第二个 DataTemplate
是否用于 DataGrid
中的项目?!
You could try to use a Binding
with the RelativeSource
property set to the FindAncestor
mode and looking for a DataGrid
object. However, I am not sure whether it will work in your scenario because I do not know how these DataTemplate
s are related to each other. Is the second DataTemplate
used for the items in the DataGrid
?!
不知何故,你的设计让我觉得很奇怪.您确定在这两种情况下都需要 DataTemplate
吗?你到底想达到什么目标?
Somehow, your design feels strange to me. Are you sure that you need DataTemplate
s in both cases? What exactly do you want to achieve?
这篇关于如何从 wpf 中的另一个数据模板访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!