简体   繁体   English

UWP x:绑定命令

[英]UWP x:Bind command

Whether it is possible so to adhere a command. 是否有可能遵守命令。

Context 语境

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

Command 命令

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

The binding itself 绑定本身

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

start but after a couple of seconds error System.StackOverflowException Why overflow error and how to overcome 启动但几秒钟后出现错误System.StackOverflowException为什么会出现溢出错误以及如何克服

When you use {x:bind} to bind the ButtonBase.Command Property, you should bind a command which will be invoked when this button is pressed. 当您使用{x:bind}绑定ButtonBase.Command属性时,应绑定一个在按下此按钮时将调用的命令。 In your code, you bind a static method which return a command, but this static method belongs to the type itself rather than to a specific object. 在您的代码中,您绑定了返回命令的静态方法,但是此静态方法属于类型本身,而不是特定对象。

To solve this error, you should delete the codes which set the page's data context object instance in the xaml. 要解决此错误,您应该删除在xaml中设置页面数据上下文对象实例的代码。 That is to delete the following code, 那就是删除下面的代码,

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

If you want to bind a command to operate the MediaElement , you should put the operation code in the command, here is a sample, 如果要绑定命令来操作MediaElement ,则应将操作代码放入命令中,这里是一个示例,

MainPage.xaml, 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 and the Command, MainPage.xaml.cs和命令,

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM