我在AppShell中设置了标题视图中的进度条。当我在页面中向前移动时,我想增加进度条。如何在其他页面中获得进度条以增加其值?
<Shell.TitleView>
<VerticalStackLayout Padding="0,10,0,0">
<HorizontalStackLayout>
<ImageButton Source="back_button_icon.png" x:Name="BackButton" Clicked="BackButton_Clicked"/>
<Image
HorizontalOptions="Center"
Margin="170,0,0,0"
Source="top_bar_icon.png"/>
</HorizontalStackLayout>
<ProgressBar
x:Name="ProgressBarPages"
Progress="0.2"
ProgressColor="#9179FF"
BackgroundColor="Transparent"/>
</VerticalStackLayout>
</Shell.TitleView>
如果你在AppShell
中设置了这个,那么你已经用x:Name
命名了你的进度条,你可以在AppShell
代码文件中获得对ProgressBarPages
控件的引用。您可以使用Shell.Current
从任何地方访问shell。所以我的建议是在你的shell中添加一个方法,例如
public void IncreaseProgress(float val)
{
// TODO: Some kind of range checking here...
ProgressBarPages.Progress += val;
}
然后从你想要的地方调用它:
(Shell.Current as AppShell)?.IncreaseProgress(.1f);
然而,我认为TitleViews
是设置在ContentPage
上的。如果它们是,那么你可能最好使用数据绑定在视图模型中设置你的进度值,无论你需要改变设置,或者使用MessagingCenter使用观察者模式来更新值?
我做类似的事情的方式,我喜欢涉及像IMessenger
从Windows社区工具包。我更喜欢这种方法,因为这种方法可以在不相关的类之间传递各种消息。还有许多其他库实现了这种模式,从Prism的EventAggregator
工作原理相同。
为了更新你的进度,你需要定义一个这样的消息:
public class ProgressValueChangedMessage: ValueChangedMessage<double>
{
public ProgressValueChangedMessage(double increment) : base(increment)
{
}
}
然后在shell中监听消息:
WeakReferenceMessenger.Default.Register<ProgressValueChangedMessage>(this, (r, m) =>
{
// increment progress
});
最后,当进度增加时,您必须在其他页面发送消息。
WeakReferenceMessenger.Default.Send(new ProgressValueChangedMessage(value));