我正在构建一个SL4应用程序。我有两个控件,一个顶部搜索栏和一个底部收藏夹栏,我希望每个页面都有。我不确定最好的办法是什么。
我当前的方法使用导航框架作为根视觉:
App.xaml.cs:
this.RootVisual = new NavFrame();
NevFrame.xaml :
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<my:TopSearchBar x:Name="topSearchBar" Grid.Row="0"/>
<navigation:Frame x:Name="navigationFrame" Source="/HomePage.xaml" Grid.Row="1"/>
<my:BottomFavoritesBar x:Name="bottomFavoritesBar" Grid.Row="2"/>
</Grid>
然后,我将更改Frame中的页面,将持久元素保留在原位。这是正确的方法,还是有其他一些首选模式?
但是,如果我这样做,我不确定如何让TopSearchBar
和BottomFavoritesBar
用户控件进行导航。 (一般情况下,我不确定如何直接从UserControl
进行导航。)
当TopSearchBar
是每个页面的成员时,我会在每个页面的代码隐藏中使用此代码:
topSearchBar.ParentPage = this;
然后 TopSearchBar
可以使用此引用进行导航:
ParentPage.NavigationService.Navigate(new Uri("/SearchPage.xaml?q=" + searchBox.Text, UriKind.Relative));
有更好的方法吗?感觉有点尴尬。如果导航需要引用页面,我该如何从NavFrame
传递该引用?
答案 0 :(得分:2)
适当的方法是将依赖项属性添加到TopSearchBar
和BottomFavoritesBar
,称为“导航器”(或任何您喜欢的),其类型为INavigate
。
你的xaml看起来像这样: -
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<my:TopSearchBar x:Name="topSearchBar" Grid.Row="0" Navigator="{Binding ElementName=navigationFrame}"/>
<navigation:Frame x:Name="navigationFrame" Source="/HomePage.xaml" Grid.Row="1"/>
<my:BottomFavoritesBar x:Name="bottomFavoritesBar" Grid.Row="2" Navigator="{Binding ElementName=navigationFrame}" />
</Grid>
现在在你的两个Bar用户控件导航中只需: -
Navigator.Navigate(new Uri("/SearchPage.xaml?q=" + searchBox.Text, UriKind.Relative));
修改强>
要创建依赖项属性,请将其添加到TopSearchBar
类: -
public INavigate Navigator
{
get { return GetValue(NavigatorProperty) as INavigate; }
set { SetValue(NavigatorProperty, value); }
}
public static readonly DependencyProperty NavigatorProperty =
DependencyProperty.Register(
"Navigator",
typeof(INavigate),
typeof(TopSearchBar),
new PropertyMetadata(null));
在BottomFavoritesBar
课程中复制此内容,但将引用更改为TopSearchBar
。
答案 1 :(得分:1)
我建议查看Prism CAL Pattern
通过这种方式,您可以为容器和要在页面之间更改的区域创建区域...这很简单,您只需更换旧区域即可替换旧区域,而其他区域保留在原位。在我看来,这是一种更加简化的方法。
http://development-guides.silverbaylabs.org/Video/Silverlight-Prism