Xamarin.Forms 应用程序中的 MasterDetailPage [英] MasterDetailPage in Xamarin.Forms App
问题描述
是否可以在 Xamarin.Forms
中创建类似的侧边菜单?
Is it possible to create a similar side menu in Xamarin.Forms
?
推荐答案
我搜索了一个小菜单.修改大小宽度为 MasterPage
I search a small menu. modify a size width to MasterPage
您可以在 MasterDetailPageRenderer
中更改 Master
页面的宽度.
You could change the width of the Master
page in MasterDetailPageRenderer
.
首先,在您的自定义 MasterDetailPage
类中创建一个 BindableProperty
:
First, create a BindableProperty
in your custom MasterDetailPage
class:
public class MyMasterDetailPage : MasterDetailPage
{
public static readonly BindableProperty DrawerWidthProperty =
BindableProperty.Create(
"WidthRatio",
typeof(int),
typeof(MyMasterDetailPage),
(float)0.2,
propertyChanged: (bindable, oldValue, newValue) =>
{
});
public float WidthRatio
{
get { return (float)GetValue(WidthRatioProperty); }
set { SetValue(WidthRatioProperty, value); }
}
}
其次,在您的 MasterDetailPageRenderer
中,像这样设置 MyMasterDetailPage
宽度:
Second, in your MasterDetailPageRenderer
, set the MyMasterDetailPage
width like this:
[assembly: ExportRenderer(typeof(MyMasterDetailPage), typeof(MyMasterDetailPageRenderer))]
...
public class MyMasterDetailPageRenderer : MasterDetailPageRenderer
{
protected override void OnElementChanged(VisualElement oldElement, VisualElement newElement)
{
base.OnElementChanged(oldElement, newElement);
var width = Resources.DisplayMetrics.WidthPixels;
var fieldInfo = GetType().BaseType.GetField("_masterLayout", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var _masterLayout = (ViewGroup)fieldInfo.GetValue(this);
var lp = new DrawerLayout.LayoutParams(_masterLayout.LayoutParameters);
MyMasterDetailPage page = (MyMasterDetailPage)newElement;
lp.Width = (int)(page.WidthRatio * width);
lp.Gravity = (int)GravityFlags.Left;
_masterLayout.LayoutParameters = lp;
}
}
用法,在我的App.xaml.cs
中,我这样设置页面:
Usage, in my App.xaml.cs
, I set the page like this:
public App()
{
InitializeComponent();
var mdp = new MyMasterDetailPage
{
Master = new MenuPage() { Title = "Master" },
Detail = new ContentPage
{
BackgroundColor = Color.White,
Title = "DetailPage",
Content = new Label
{
Text = "DetailPage",
HorizontalTextAlignment = TextAlignment.Center,
VerticalTextAlignment = TextAlignment.Center,
},
},
WidthRatio = 0.5f,
};
MainPage = mdp;
}
更新:
关于Xamarin.iOS
,可以参考this,灵感来自P3PPP的项目,你唯一的需要做的是在 MyPhoneMasterDetailRenderer.cs 中更改这一行:
Update:
About Xamarin.iOS
, you could refer to this, inspired by P3PPP's project, the only thing you need do is change this line in MyPhoneMasterDetailRenderer.cs:
//Change 0.8 to whatever you want
masterFrame.Width = (int)(Math.Min(masterFrame.Width, masterFrame.Height) * 0.8);
这篇关于Xamarin.Forms 应用程序中的 MasterDetailPage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!