我的Xamarin Forms项目上有一个选项卡式页面。这些选项卡过去一直在滑动,但是我已经实现了CustomRender来阻止这种情况。
这很好用,除了需要将页面重新添加到标签栏时。我似乎无法重新使用自定义渲染?
现在,我要像这样将页面重新添加到CustomRendered TabbedPage中:
var masterTabPage = this.Parent.Parent as NoSlideTabbedPage;
Xamarin.Forms.NavigationPage Page1 = new Xamarin.Forms.NavigationPage(new Page1("example string"));
Page1.Title = "Page Example";
Page1.Icon = "pageexample.png";
masterTabPage.Children.RemoveAt(1);
masterTabPage.Children.Insert(1, Page1);
masterTabPage.CurrentPage = masterTabPage.Children[1];
我的布局页面看起来像
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Layout : NoSlideTabbedPage
{
public Layout()
{
InitializeComponent();
On<Android>().SetBarItemColor(Color.FromHex("#cccccc"));
On<Android>().SetBarSelectedItemColor(Color.FromHex("#123456"));
// SET NAV BAR TO BOTTOM
On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
// CREATE TABS
NavigationPage Page0 = new NavigationPage(new Page0());
Page0.Title = "Page0";
Page0.Icon = "Page0.png";
NavigationPage Page1 = new NavigationPage(new Page1());
Page1.Title = "Page1";
Page1.Icon = "Page1.png";
NavigationPage Page2 = new NavigationPage(new Page2());
Page2.Title = "Page2";
Page2.Icon = "Page2.png";
NavigationPage Page3 = new NavigationPage(new Page3());
Page3.Title = "Page3";
Page3.Icon = "Page3.png";
// ADD TABS
Children.Add(Page0);
Children.Add(Page1);
Children.Add(Page2);
Children.Add(Page3);
}
}
CustomRenderer的代码:
public class NoSlideTabbedPageRenderer : TabbedPageRenderer
{
private bool _isShiftModeSet;
public NoSlideTabbedPageRenderer(Context context)
: base(context)
{
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
try
{
if (!_isShiftModeSet)
{
var children = GetAllChildViews(ViewGroup);
if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
{
bottomNav.SetShiftMode(false, false);
_isShiftModeSet = true;
}
}
}
catch (Exception e)
{
Console.WriteLine($"Error setting ShiftMode: {e}");
}
}
private List<View> GetAllChildViews(View view)
{
if (!(view is ViewGroup group))
{
return new List<View> { view };
}
var result = new List<View>();
for (int i = 0; i < group.ChildCount; i++)
{
var child = group.GetChildAt(i);
var childList = new List<View> { child };
childList.AddRange(GetAllChildViews(child));
result.AddRange(childList);
}
return result.Distinct().ToList();
}
}
布局页面正常工作,因为我正在使用上面的CustomRender。这样可以使选项卡正常。但是,当我删除并重新添加页面时(显示在第一个代码块中),CustomRender停止使用。 在仍然重新添加此Page1的同时,如何保持使用该自定义渲染?
答案 0 :(得分:2)
您可以收听元素更改的属性,然后再次调用shiftmode。
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
if(e.NewElement !=null)
{
var children = GetAllChildViews(ViewGroup);
if (children.SingleOrDefault(x => x is BottomNavigationView) is BottomNavigationView bottomNav)
{
bottomNav.SetShiftMode(false, false);
_isShiftModeSet = true;
}
}
}