2010-10-19 73 views
0

有沒有辦法直接從xaml調用外部對象的方法(例如資源對象)?有沒有辦法從xaml調用外部函數?

我的意思是這樣的:

<Grid xmlns:dm="clr-namespace:MyNameSpace;assembly=MyAssembly"> 
    <Grid.Resources> 
     <dm:TimeSource x:Key="timesource1"/> 
    </Grid.Resources> 

    <Button Click="timesource_updade">Update time</Button> 
</Grid> 

方法timesource_update當然是TIMESOURCE對象的方法。

我需要使用純粹的XAML,而不是任何背後的代碼。

回答

1

好的,這裏是最終的溶劑。

XAML:

<Grid xmlns:dm="clr-namespace:MyNameSpace;assembly=MyAssembly"> 
     <Grid.Resources> 
      <dm:TimeSource x:Key="timesource1"/> 
     </Grid.Resources> 

     <Button Command="{x:Static dm:TimeSource.Update}" 
       CommandParameter="any_parameter" 
       CommandTarget="{Binding Source={StaticResource timesource1}}">Update time</Button> 
    </Grid> 

CODE在TIMESOURCE類:

public class TimeSource : System.Windows.UIElement { 

    public static RoutedCommand Update = new RoutedCommand(); 

    private void UpdateExecuted(object sender, ExecutedRoutedEventArgs e) 
    { 
     // code 
    } 

    private void UpdateCanExecute(object sender, CanExecuteRoutedEventArgs e) 
    { 
     e.CanExecute = true; 
    } 

    // Constructor 
    public TimeSource() { 

    CommandBinding cb = new CommandBinding(TimeSource.Update, UpdateExecuted, UpdateCanExecute); 
    CommandBindings.Add(cb2); 
    } 
} 

TIMESOURCE已經以自UIElement爲了具有化CommandBindings導出。但結果是直接從XAML調用外部裝配方法。通過點擊按鈕,對象timesource1的'UpdateExecuted'方法被調用,這正是我正在尋找的。

1

檢查this線程,它有一個類似的問題。一般來說,您不能直接從xaml調用方法。 您可以使用命令,或者您可以從xaml創建一個對象,它將在線程上創建一個方法,該方法將在需要時自行處理。

但是我擔心你不能在純粹的XAML中做到這一點。在C#中,您可以在XAML中完成所有可以完成的任務,但不能以其他方式完成。你只能從XAML中做一些你可以在C#中完成的事情。

+0

這表明我非常好的方向。感謝您的幫助,並查看我的最終溶劑。 – Gal 2010-10-20 08:36:05

相關問題