2015-03-02 32 views
0

我有一個我正在加載到ItemsControl中的事務列表,但我想在每行/事務中顯示來自我的viewmodel的UserId。 userId不在事務列表中,它是我試圖訪問的viewmodel中的一個屬性,但似乎我嘗試過的所有內容都不起作用,我不知道爲什麼。我所得到的是一個空白列值。 (是的,我確認這個屬性並不是空的,甚至硬編碼了一個值,什麼也沒有)。XAML Itemscontrol綁定到控件之外的屬性

我的理解是我應該能夠使用具有窗口AncestorType的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> 

回答

1

儘管它在Window的DataContext中,但您的RelativeSource綁定嘗試在父窗口中查找該屬性。

以下應該工作,前提是UserId屬性是相同的視圖模型類爲MyReportResult

<TextBlock Text="{Binding Path=DataContext.UserId, 
        RelativeSource={RelativeSource AncestorType=ItemsControl}}"/> 
+0

(捂臉)我從來沒有想過使用AncestorType = ItemsControl的。我正在嘗試幾乎所有其他類型,漫長的夜晚。謝謝@Clemens! – devfunkd 2015-03-02 16:07:23

0

只有WPF支持的RelativeSource,因爲它不是絕對必要的。使用ElementName的方式不那麼脆弱:

首先,爲您的頂級對象或其子級(通常爲網格)指定一個x:Name =「something」。

文本= 「{綁定路徑= DataContext.UserId,元=東西}」

相關問題