【发布时间】:2014-06-01 01:04:20
【问题描述】:
我正在尝试在 Windows 应用商店应用程序中有效使用 TopAppBar。我使用了基本页面模板,并以与实现 GoForwardCommand 和 GoBackCommand 相同的方式将 NavigateCommand 添加到 NavigationHelper 类。我还在 RelayCommand 中添加了一个构造函数,以使 Execute 和 CanExecute 委托能够获取对象参数
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_executeWithParam = execute;
_canExecuteWithParam = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? (_canExecuteWithParam == null ? true : _canExecuteWithParam(parameter)) : _canExecute();
}
public void Execute(object parameter)
{
if (_execute == null)
_executeWithParam(parameter);
else
_execute();
}
在我的 MainPage XAML 中,我有以下代码:
<Page
x:Name="pageRoot"
x:Class="UniAppTest.MainPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:UniAppTest"
xmlns:common="using:UniAppTest.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
<x:String x:Key="AppName">Welcome to universal apps!</x:String>
</Page.Resources>
<Page.TopAppBar>
<AppBar>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Button Content="Home" Width="140" Height="80" />
<Button Content="Summary" Width="140" Height="80"
Command="{Binding NavigateCommand}"
CommandParameter="SummaryPage" />
<Button Content="Reports" Width="140" Height="80"
Command="{Binding NavigationHelper.NavigateCommand, ElementName=pageRoot}"
CommandParameter="ReportsPage " />
</StackPanel>
<SearchBox Grid.Column="1" Width="300" Height="50" HorizontalAlignment="Right" />
</Grid>
</AppBar>
</Page.TopAppBar>
两个按钮都不会在按下时调用命令。
但是,如果我在主页内容中添加一个按钮,则该命令会成功运行:
<Button x:Name="summaryButton" Margin="39,59,39,0"
Command="{Binding NavigationHelper.NavigateCommand, ElementName=pageRoot}"
CommandParameter="SummaryPage"
Grid.Row="1" Content="Summary"
Style="{StaticResource TextBlockButtonStyle}"
VerticalAlignment="Top"
FontSize="24"/>
谁能帮我看看我做错了什么。我认为它必须在 Binding 参考中。我总是觉得这很令人困惑。将不胜感激任何帮助。谢谢。
【问题讨论】:
-
也许应用栏有一个单独的名称范围。您可以检查 Visual Studio 输出窗口中的绑定错误消息吗?
标签: windows binding command windows-store-apps winrt-xaml