我有一个我正在加载到ItemsControl中的事务列表,但我希望在每行/事务中显示来自viewmodel的UserId。 userId不在事务列表中,它是我试图访问的viewmodel中的属性,但似乎我尝试过的所有内容都不起作用,我不知道为什么。我得到的只是一个空白列值。 (是的,我确认该属性不是空的。甚至硬编码了一个值,什么都没有)。
我的理解是我应该能够使用具有AncestorType of Window的RelativeSource来访问该属性。我错过了什么吗?
<ItemsControl ItemsSource="{Binding Path=MyReportResult.Transactions}" KeyboardNavigation.IsTabStop="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="20 2 0 2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".15*"/>
<ColumnDefinition Width=".15*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" TextAlignment="Center" Margin="10 0 20 0" Text="{Binding Path=UserId, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"></TextBlock>
<TextBlock Grid.Column="0" TextAlignment="Center" Margin="10 0 20 0" Text="{Binding Path=Amount}"></TextBlock>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
答案 0 :(得分:1)
您的RelativeSource绑定尝试在父窗口中查找属性,尽管它位于Window的DataContext中。
如果UserId
属性与MyReportResult
在同一个视图模型类中,则以下内容应该有效:
<TextBlock Text="{Binding Path=DataContext.UserId,
RelativeSource={RelativeSource AncestorType=ItemsControl}}"/>
答案 1 :(得分:0)
只有WPF支持RelativeSource,因为它不是绝对必要的。使用ElementName不那么脆弱,如下所示:
首先,给一个x:Name =&#34;某事&#34;到您的顶级对象或其子级(通常是网格)。
Text =&#34; {Binding Path = DataContext.UserId,Element = something}&#34;