2016-12-08 33 views
1

下午好,我正在寫這個問題,看看您是否可以幫我解決我遇到的問題,這可能很容易解決,但我一直無法做到它工作幾天。如何從WPF ItemsControls的標籤中獲取價值

WPF編程我創建了一個itemscontrols,其中列出了我擁有的所有書籍的列表,直到出現一切完美的作品,我的問題是,當我按下按鈕時,我想這樣做我將名稱的值該書在另一部分使用它。

然後我離開,我有這樣我可以理解的代碼片段多一點

<StackPanel Name="stkMain"> 
    <ItemsControl Name="itmCntrl"> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate> 
       <WrapPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" ></WrapPanel> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <StackPanel Name="stk"> 
         <materialDesign:Card Width="300" Margin="10" VerticalAlignment="Stretch"> 
          <Grid> 

           <Grid.RowDefinitions> 
            <RowDefinition Height="*" /> 
            <RowDefinition Height="Auto" /> 
           </Grid.RowDefinitions> 
           <Image Name="img" Source="{Binding PhotoPath}" Height="300" Width="240" Stretch="Fill" Cursor="Hand" /> 
            <Button Grid.Row="1" Grid.Column="1" Style="{DynamicResource MaterialDesignFlatButton}" Content="MORE" 
             HorizontalAlignment="Right" Margin="8" Click="Button_Click"/> 
            <Label x:Name="nan" Content="{Binding Name}"></Label> 
          </Grid> 
         </materialDesign:Card> 
        </materialDesign:TransitioningContent> 
       </StackPanel> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</StackPanel> 

正如你可以看到每個項目創建我有一個形象,一個標籤和一個按鈕,基本上我不能做的是通過按下按鈕我拿着標籤的價值

我希望我可以幫助這個。

謝謝。

回答

1

in a Button_Click方法sender參數是一個具有DataContext屬性的按鈕。 DataContextName屬性的單個對象:

// c# 
Button b = (Button)sender; 
object dc = b.DataContext; 
//// cast dc to correct type, e.g. 
// Book book = (Book)dc; 
// string name = book.Name; 
+0

非常感謝你,我的工作很好,這是你告訴我的人。 – alex