2014-03-29 80 views
1

代碼控制我有問題,這樣的代碼:訪問的DataTemplate在後面

<ListBox x:Name="lbInvoice" ItemsSource="{Binding ocItemsinInvoice}"> 
<ListBox.ItemTemplate> 
    <DataTemplate> 
     <StackPanel> 
      <ToggleButton x:Name="btnInvoiceItem"> 
       <StackPanel Orientation="Horizontal"> 
        <ToggleButton x:Name="btnInvoiceQuantity" Content="{Binding Quantity}"/> 
        <TextBlock Text="{Binding Item.ItemName}" Width="175" Padding="7,5,0,0"/> 
       </StackPanel> 
      </ToggleButton> 
      <Popup x:Name="popQuantity" Closed="popQuantity_Closed" PlacementTarget="{Binding ElementName=btnInvoiceQuantity}" IsOpen="{Binding IsChecked,ElementName=btnInvoiceQuantity}"> 
        <Grid> 
         <TextBlock x:Name="tbUnitPrice" Text="Unit Price"/> 
         <Button x:Name="btnClosePopup" Click="btnClosePopup_Click"> 
        </Grid> 
      </Popup> 
     </StackPanel> 
    </DataTemplate> 
</ListBox.ItemTemplate> 

在後面的代碼中btnClosePopup單擊事件我無法訪問彈出關閉它和做一些其他的變化它。

我曾嘗試使用FindName()方法,但它並沒有爲我工作

var template = lbInvoice.Template; 
var myControl = (Popup)template.FindName("popQuantity", lbInvoice); 

請你能幫助,告訴我我該如何訪問控制裏面的DataTemplate在後面的代碼?

回答

1

做到這一點,你已經在這條線Open/ClosePopup

IsOpen="{Binding IsChecked, ElementName=btnInvoiceQuantity}" 

如從@dkozl一個備選答案,你可以這樣關閉Popup

<Popup x:Name="popQuantity" 
     IsOpen="{Binding Path=IsChecked, ElementName=btnInvoiceQuantity}"> 

    <Grid Width="200" Height="200" Background="Gainsboro"> 
     <TextBlock Text="Unit Price" /> 

     <ToggleButton x:Name="btnClosePopup" 
         IsChecked="{Binding Path=IsChecked, ElementName=btnInvoiceQuantity}" 
         Content="Close" 
         Width="100" 
         Height="30" /> 
    </Grid> 
</Popup> 

或者你也可以直接指定IFY屬性IsOpen彈出的:

<ToggleButton x:Name="btnClosePopup" 
       IsChecked="{Binding Path=IsOpen, ElementName=popQuantity}" ... /> 

但在這種情況下,在Button背景顏色將在IsChecked="True"狀態。爲了避免這種情況,而無需創建爲您控制的新模板,你可以使用平板按鈕的系統風格:

<ToggleButton x:Name="btnClosePopup" 
       Style="{StaticResource {x:Static ToolBar.ToggleButtonStyleKey}}" ... /> 
+0

感謝@Anatoliy尼古拉耶夫 –

2

您不必在代碼背後執行此操作,如果您在代碼中更改Popup.IsOpen,它將不會再顯示,因爲您將失去約束力。您需要在ToggleButton設置IsChecked爲false,你可以用EventTrigger

<Button Content="Close" x:Name="btnClosePopup"> 
    <Button.Triggers> 
     <EventTrigger RoutedEvent="Button.Click"> 
     <BeginStoryboard> 
      <Storyboard> 
       <BooleanAnimationUsingKeyFrames Storyboard.TargetName=" btnInvoiceQuantity" Storyboard.TargetProperty="IsChecked"> 
        <DiscreteBooleanKeyFrame Value="False" KeyTime="0:0:0"/> 
       </BooleanAnimationUsingKeyFrames> 
      </Storyboard> 
     </BeginStoryboard> 
     </EventTrigger> 
    </Button.Triggers> 
</Button> 
+1

感謝@dkozl您的時間 –