views:

20

answers:

2

Is there any way to call methods of external objects (for example resource objects) directly from xaml?

I mean something like this:

<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>

The method timesource_update is of course the method of the TimeSource object.

I need to use pure XAML, not any code behind.

+1  A: 

Check this thread, it has a similar problem. In general you can't call a method directly from xaml. You could use Commands or you can create an object from xaml which will create a method on a thread, which will dispose itself when it needs.

But I am afraid you can't do it just in pure XAML. In C# you can do everything you can do in XAML, but not other way round. You can only do some certain things from XAML that you can do in C#.

Vitalij
This pointed me definitelly good direction. Thanks for help and check out my final sollution below.
Gal
A: 

OK, here is the final sollution.

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 in the TimeSource class:

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 has to be derived from UIElement in order to have CommandBindings. But the result is calling outer assembly method directly from XAML. By clicking the button, 'UpdateExecuted' method of the object timesource1 is called and that is exactly what I was looking for.

Gal