【问题标题】:Is there a way to call external functions from xaml?有没有办法从 xaml 调用外部函数?
【发布时间】:2011-04-27 10:47:08
【问题描述】:

有没有办法直接从 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,而不是任何代码。

【问题讨论】:

标签: wpf xaml resources methods call


【解决方案1】:

检查this线程,它有类似的问题。通常,您不能直接从 xaml 调用方法。 您可以使用命令,也可以从 xaml 创建一个对象,该对象将在线程上创建一个方法,该方法将在需要时自行处理。

但恐怕你不能只在纯 XAML 中做到这一点。在 C# 中,您可以做所有在 XAML 中可以做的事情,但不能反过来。您只能通过 XAML 执行某些可以在 C# 中执行的操作。

【讨论】:

  • 这为我指明了方向。感谢您的帮助,并在下面查看我的最终解决方案。
【解决方案2】:

好的,这是最终的解决方案。

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>

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”方法被调用,这正是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    相关资源
    最近更新 更多