2013-05-22 28 views
2

我在我的應用程序中有一個MainWindow。 在主窗口中,我動態地託管一個用戶控件(ucA)。 在ucA內我有另一個用戶控件(ucB)。跨越用戶控件執行功能wpf c#

當我點擊ucB上的保存按鈕時,我需要在ucA上執行一個例程。

我該如何參考ucA上的例程?

回答

1

這裏有一些方法我能想到的: -

您可以使用CallMethodAction在XAML中調用父用戶控件的方法。該代碼是這樣的: -

<UserControl x:Class="WpfApplication.ucB" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
    Height="300" Width="300"> 
<StackPanel> 
    <Button Content="Save" x:Name="SaveButton" > 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="Click"> 
       <ei:CallMethodAction TargetObject="{Binding RelativeSource={RelativeSource FindAncestor, AncestorLevel=2, AncestorType=UserControl}}" 
           MethodName="MethodToCallOnucA" /> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
    </Button>   

</StackPanel> 

這樣你就可以調用UCA的方法,它是UCB的父母。但是這種從xaml調用方法的方式存在很大的侷限性。限制是在這種情況下,您的`MethodToCallOnucA'必須返回void並且必須沒有方法參數。

如果你必須發送參數給你的方法,那麼你需要按照這裏的第二種方法。爲此,我們需要使用Commands來調用Usercontrol的方法。您需要更改按鈕的代碼在XAML上面是這樣的: -

<Button Content="Save" x:Name="SaveButton" > 
     <i:Interaction.Triggers> 
      <i:EventTrigger EventName="Click"> 
       <i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorLevel=2, AncestorType=UserControl}, Path=DoActionCommand}" CommandParameter="ValueToSendAsMethodParameter" /> 
      </i:EventTrigger> 
     </i:Interaction.Triggers> 
    </Button> 

這裏DoActionCommand是在你的用戶控件UCA這ICommand的點,你需要在UCA調用該方法定義的ICommand的屬性。

+0

會給這個試試看。 期待對此進行測試。 –