【发布时间】:2016-02-01 09:54:35
【问题描述】:
我正在构建一个使用 MVVM 的应用程序,并尝试将命令绑定到本教程中所示的按钮:
但是,我无法使绑定工作 - 当我单击 HyperlinkButton 并且我在 Execute 方法开头放置的断点没有触发时,没有任何反应。
这是我的 ViewModel:
public class ArticleListViewModel
{
public IEnumerable<ArticleItem> Items { get; set; }
public async Task PopulateArticles()
{
// ...
}
}
public class ArticleItem
{
public ArticleItem()
{
OpenLinkCommand = new OpenArticleLinkCommand();
}
public ICommand OpenLinkCommand;
public string Url { get; set; }
public string Title { get; set; }
}
OpenArticleLinkCommand.cs:
public class OpenArticleLinkCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public async void Execute(object parameter)
{
var article = parameter as ArticleItem;
if (article != null)
{
var success = await Launcher.LaunchUriAsync(new Uri(article.Url));
//TODO: handle success/fail
}
}
}
这是我的视图的样子:
<UserControl
x:Class="LTNewsFeed.Views.ArticleItemView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LTNewsFeed.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<ListBox ItemsSource="{Binding}" x:Name="mainListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<HyperlinkButton x:Name="Title"
Content="{Binding Path=Title, Mode=OneWay}"
Command="{Binding OpenLinkCommand}"
Grid.Column="0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UserControl>
主页.xaml:
<Page
x:Class="LTNewsFeed.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:LTNewsFeed"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:LTNewsFeed.Views"
xmlns:src="using:LTNewsFeed"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<views:ArticleItemView x:Name="ItemsOnPage" />
</Grid>
</Page>
我在 MainPage.xaml.cs 中填充视图模型项集合:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await viewModel.PopulateArticles();
ItemsOnPage.DataContext = viewModel.Items;
}
我尝试过但没有成功的事情:
- 引用
DataContext并指定ElementName,如this answer 中所建议的那样。 - 将 HyperlinkButton 更改为简单按钮。
- 将
OpenArticleLinkCommand移动到与我的ArticleItem模型相同的文件中,以防无法识别命名空间。 - 在 Google 和 StackOverflow 上浏览类似问题 - 在我看来,我所做的一切都与示例中的相同。
任何为我指明正确方向的帮助,或描述我如何调试此类东西的帮助将不胜感激。
【问题讨论】:
-
你看到列表框中的项目了吗?
-
我怀疑你在 Execute 函数中的转换失败了
标签: c# xaml mvvm windows-phone-8.1 icommand