C# uwpx:Bind命令
是否有可能遵守命令 上下文C# uwpx:Bind命令,c#,data-binding,uwp,uwp-xaml,C#,Data Binding,Uwp,Uwp Xaml,是否有可能遵守命令 上下文 <Page.DataContext> <local: MainPage /> </Page.DataContext> 装订本身 <Button VerticalAlignment = "Bottom" Margin = "10,0,0,10" Command = "{x: Bind local: MainPage.Pause (mp)}"
<Page.DataContext>
<local: MainPage />
</Page.DataContext>
装订本身
<Button VerticalAlignment = "Bottom"
Margin = "10,0,0,10" Command = "{x: Bind local: MainPage.Pause (mp)}"
HorizontalAlignment = "Left" Height = "30" Width = "100"> Pause </ Button>
暂停
开始,但几秒钟后出现错误
System.StackOverflowException
为什么出现溢出错误以及如何克服当您使用绑定属性时,应绑定一个命令,按下此按钮时将调用该命令。在代码中,您绑定了一个返回命令的静态方法,但是这个静态方法属于类型本身,而不是特定对象
要解决此错误,应删除在xaml中设置页面数据上下文对象实例的代码。即删除以下代码
<Page.DataContext>
<local:MainPage />
</Page.DataContext>
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);
}
}
公共密封部分类主页面:第页
{
公共主页()
{
this.InitializeComponent();
}
公共静态命令暂停(MediaElement)
{
//元素Pause();
返回新命令(s=>{element.Pause();},true);
}
}
公共类命令:ICommand
{
私人行动;
私人布尔canExecute;
公共事件处理程序CanExecuteChanged;
公共命令(动作动作,布尔canExecute)
{
这个动作=动作;
this.canExecute=canExecute;
}
公共布尔CanExecute(对象参数)
{
返回canExecute;
}
public void Execute(对象参数)
{
作用(参数);
}
}
<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>
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);
}
}