开发者

Is there a way to call external functions from xaml?

开发者 https://www.devze.com 2023-01-20 15:11 出处:网络
Is there any way to call methods of external objects (for example resource objects) directly from xaml?

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开发者_如何学Go use pure XAML, not any code behind.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消