C# UWP-命令参数为空
我使用的是微软在其C# UWP-命令参数为空,c#,xaml,mvvm,uwp,icommand,C#,Xaml,Mvvm,Uwp,Icommand,我使用的是微软在其ICommand中实现的RelayCommand。下面是我的代码简介 XAML: XAML背后的代码: 公共密封部分类UrlSearchPage:第页 { 公共UrlSearchViewModel UrlSearchViewModel; 公共URL搜索页面() { this.InitializeComponent(); urlSearchViewModel=新的urlSearchViewModel(); } } 视图模型代码: public RelayCommand\u
ICommand
中实现的RelayCommand
。下面是我的代码简介
XAML:
XAML背后的代码:
公共密封部分类UrlSearchPage:第页
{
公共UrlSearchViewModel UrlSearchViewModel;
公共URL搜索页面()
{
this.InitializeComponent();
urlSearchViewModel=新的urlSearchViewModel();
}
}
视图模型代码:
public RelayCommand\u GetVideo(字符串url)
{
返回新的RelayCommand(()=>this.getVideo(url));
}
私有视频(字符串url)
{
尝试
{
FileInfo mp4=youtubeConverter.downloaddvideoasync(url,youtubeConverter.TemporaryFolder).GetAwaiter().GetResult();
}
捕获(例外情况除外)
{
Debug.WriteLine(例如消息);
}
}
例如,忽略愚蠢的异步部分。问题是url
始终是一个空字符串,因此每次我按下按钮时都会收到异常
UWP-命令参数为空
恐怕您不能用包含参数且返回类型为RelayCommand
的方法绑定命令。请参考以下代码,编辑命令,并使用CommandParameter
属性传递参数
public class UrlSearchViewModel
{
public ICommand GetVideo
{
get
{
return new CommadEventHandler<string>((s) => this.getVideo(s));
}
}
private void getVideo(string url)
{
try
{
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
public class CommadEventHandler<T> : ICommand
{
public event EventHandler CanExecuteChanged;
public Action<T> action;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
this.action((T)parameter);
}
public CommadEventHandler(Action<T> action)
{
this.action = action;
}
}
公共类UrlSearchViewModel
{
公共ICommand GetVideo
{
得到
{
返回新的CommadEventHandler((s)=>this.getVideo);
}
}
私有视频(字符串url)
{
尝试
{
}
捕获(例外情况除外)
{
Debug.WriteLine(例如消息);
}
}
}
公共类CommadEventHandler:ICommand
{
公共事件处理程序CanExecuteChanged;
公共行动;
公共布尔CanExecute(对象参数)
{
返回true;
}
public void Execute(对象参数)
{
这个动作((T)参数);
}
公共通讯员(行动)
{
这个动作=动作;
}
}
Xaml
<Grid Background="GreenYellow">
<TextBox
x:Name="YoutubeUrlText"
Width="450"
VerticalAlignment="Top"
FontSize="20"
FontStyle="Italic"
PlaceholderText="Insert link from youtube here... "
/>
<Button
x:Name="ConvertButton"
Grid.Column="1"
Height="40"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Background="#FF0096FF"
BorderBrush="#FF797979"
Command="{x:Bind urlSearchViewModel.GetVideo}"
CommandParameter="{Binding ElementName=YoutubeUrlText,Path=Text}"
Content=""
FontFamily="Segoe MDL2 Assets"
FontSize="20"
Foreground="White"
/>
</Grid>
CommandParameter=“{x:Bind YoutubeUrlText.Text,Mode=OneWay}”
将此添加到按钮中,并且仅此命令=“{x:Bind urlSearchViewModel.\u GetVideo}”
@RaoHammas这样会导致Visual Studio“找不到属性”。我想你说的是Binding
而不是x:Bind
。顺便说一句,我试过了,但没有用