我正在使用 Xamarin Forms 构建移动应用程序。我的问题是我有一个 NewBlockButton,当按下它时,需要打开一个带有标题和 2 个按钮的弹出页面。我正在使用 Xamarin Community Toolkit 来弹出窗口。 主页
using MathTab.View_Model;
using Xamarin.Forms;
namespace MathTab
{
public partial class MainPage : ContentPage
{
public MainPage()
{
var backgroundImage = new Image
{
Source = "Background.jpg",
Aspect = Aspect.AspectFill
};
Button NewBlockButton = new Button
{
Text = "+",
TextColor = Color.Black,
BackgroundColor = Color.Gray,
Margin = new Thickness(10)
};
NewBlockButton.SetBinding(Button.CommandProperty, new Binding(nameof(MainPageViewModel.NewBlockCommand)));
Grid grid = new Grid
{
RowDefinitions =
{
new RowDefinition{Height=new GridLength(9,GridUnitType.Star)},
new RowDefinition{Height=new GridLength(1,GridUnitType.Star)}
},
ColumnDefinitions =
{
new ColumnDefinition{Width=new GridLength (1, GridUnitType.Star)}
}
};
grid.BackgroundColor = Color.Purple;
grid.Children.Add(backgroundImage,0,0);
grid.Children.Add(NewBlockButton,0,1);
Content= grid;
}
}
}
主页视图模型
using MathTab.View;
using System.ComponentModel;
using Xamarin.CommunityToolkit.Extensions;
using Xamarin.CommunityToolkit.ObjectModel;
namespace MathTab.View_Model
{
internal class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public AsyncCommand NewBlockCommand { get; }
public MainPageViewModel()
{
NewBlockCommand = new AsyncCommand(async () =>
{
var popupViewModel = new NewBlockPopupViewModel();
var popupPage =new NewBlockPopup();
await App.Current.MainPage.Navigation.ShowPopupAsync(popupPage);
});
}
}
}
弹出窗口
using MathTab.View_Model;
using Xamarin.CommunityToolkit.UI.Views;
using Xamarin.Forms;
namespace MathTab.View
{
internal class NewBlockPopup : Popup
{
public NewBlockPopup()
{
Label title = new Label
{
Text = "New Block"
};
Button newTextBlockButton=new Button
{
Text = "Text"
};
Button newMathBlockButton = new Button
{
Text = "Mathematics"
};
newMathBlockButton.SetBinding(Button.CommandProperty, nameof(NewBlockPopupViewModel.NewMathBlockCommand));
newTextBlockButton.SetBinding(Button.CommandProperty, nameof(NewBlockPopupViewModel.NewTextBlockCommand));
Grid grid = new Grid
{
RowDefinitions =
{
new RowDefinition{Height=new GridLength(3,GridUnitType.Star)},
new RowDefinition{Height=new GridLength(1,GridUnitType.Star)},
},
ColumnDefinitions =
{
new ColumnDefinition{Width=new GridLength (1, GridUnitType.Star)},
new ColumnDefinition{Width=new GridLength (1, GridUnitType.Star)}
}
};
grid.Children.Add(newTextBlockButton,1,0);
grid.Children.Add(newMathBlockButton, 1, 1);
grid.Children.Add(title, 0, 0);
Grid.SetColumnSpan(title, 2);
Content = grid;
}
}
}
调试时,似乎按下按钮时,不会启动按钮的命令。
Binding
仅当您为页面分配 BindingContext
时才有效
public MainPage()
{
this.BindingContext = new MainPageViewModel();
...