UWP x:绑定命令

时间:2018-05-30 15:54:58

标签: c# data-binding uwp uwp-xaml

是否可以遵守命令。

上下文

/**
* @snippet       WooCommerce Show Product Subcategories
* @compatible    WooCommerce 3.4
*/

add_action( 
'woocommerce_after_shop_loop_item_title','bbloomer_show_all_subcats', 2 );

function bbloomer_show_all_subcats() {

// Create array with product categories that belong to current product

$cats = get_the_terms( $post->ID, 'product_cat' );

if ( ! empty( $cats ) ) {

// Loop through the product categories...

    foreach ( $cats as $term ) {

                    // If parent cat ID = 116 echo subcat name...
        if( $term->parent == 116 ) { echo $term->name; }

    }

    }

  }

命令

<Page.DataContext>
         <local: MainPage />
     </Page.DataContext>

绑定本身

static public Command Pause (MediaElement element)
         {
             element.Pause ();
             return new Command ();
         }

开始但是几秒钟后错误 System.StackOverflowException 为什么溢出错误以及如何克服

1 个答案:

答案 0 :(得分:2)

使用{x:bind}绑定ButtonBase.Command属性时,应该绑定一个命令,按下此按钮时将调用该命令。在您的代码中,绑定一个返回命令的静态方法,但此静态方法属于类型本身而不是特定对象。

要解决此错误,您应该删除在xaml中设置页面的数据上下文对象实例的代码。那就是删除以下代码,

<Page.DataContext>
    <local:MainPage />
</Page.DataContext>

如果要绑定命令来操作MediaElement,您应该将操作代码放在命令中,这是一个示例,

MainPage.xaml中,

<StackPanel>
    <MediaElement Name="mp" Width="800" Height="400" Source="ms-appx:///Assets/video.mp4"/>

    <Button VerticalAlignment = "Bottom" Margin = "10,0,0,10" Command = "{x:Bind local:MainPage.Pause(mp)}"
             HorizontalAlignment = "Left" Height = "30" Width = "100">Pause</Button>
</StackPanel>

MainPage.xaml.cs和Command,

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    public static Command Pause(MediaElement element)
    {
        //element.Pause();
        return new Command(s => { element.Pause(); },true);
    }
}

public class Command : ICommand
{
    private Action<object> action;
    private bool canExecute;
    public event EventHandler CanExecuteChanged;

    public Command(Action<object> action,bool canExecute)
    {
        this.action = action;
        this.canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return canExecute;
    }

    public void Execute(object parameter)
    {
        action(parameter);
    }
}