UWP-命令参数为空



我使用的是微软在ICommand示例中实现的RelayCommand。这是我的代码简介。

XAML:

<TextBox x:Name="YoutubeUrlText"
PlaceholderText="Insert link from youtube here... "
FontSize="20" FontStyle="Italic" Width="450" />
<Button x:Name="ConvertButton" FontFamily="Segoe MDL2 Assets" FontSize="20" Content="&#xE751;"
Grid.Column="1" Height="40"
HorizontalAlignment="Left" VerticalAlignment="Center" 
Foreground="White" BorderBrush="#FF797979" Background="#FF0096FF" 
Command="{x:Bind urlSearchViewModel._GetVideo(YoutubeUrlText.Text)}"/>

XAML背后的代码:

public sealed partial class UrlSearchPage : Page
{
public UrlSearchViewModel urlSearchViewModel;
public UrlSearchPage()
{
this.InitializeComponent();
urlSearchViewModel = new UrlSearchViewModel();
}
}

ViewModel代码:

public RelayCommand _GetVideo(string url)
{
return new RelayCommand(() => this.getVideo(url));
}
private void getVideo(string url)
{
try
{
FileInfo mp4 = youtubeConverter.DownloadVideoAsync(url, YoutubeConverter.TemporaryFolder).GetAwaiter().GetResult();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}

例如,忽略愚蠢的异步部分。问题是url总是一个空字符串,所以每次按下Button时我都会收到一个Exception

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

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="&#xE751;"
FontFamily="Segoe MDL2 Assets"
FontSize="20"
Foreground="White"
/>
</Grid>

最新更新