下面是类“InqueritoViewModel”的绑定上下文,在XAML中一切正常。我可以毫无问题地调用命令“GetinqueritoCommand”,但现在我正在尝试使用C#代替XAML进行设计,但我不能从“InqueritoViewModel”类中调用“GetinqueritoCommand”。
为什么我无法访问命令?我正在内容中进行Bindingcontext。
public class InqueritoViewModel : INotifyPropertyChanged
{
ApiServices _apiServices = new ApiServices();
public List<Inquerito> _inqueritos;
public string AccessToken { get; set; }
public List<Inquerito> Inqueritos
{
get { return _inqueritos; }
set
{
_inqueritos = value;
OnPropertyChanged();
}
}
public ICommand GetinqueritoCommand
{
get
{
return new Command(async () =>
{
AccessToken = Settings.AccessToken;
Inqueritos = await _apiServices.GetinqueritosAsync(AccessToken);
});
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
InqueritoViewModel:
public class Inqueritoscode : ContentPage
{
public Inqueritoscode()
{
ListView listView = new ListView
{
HasUnevenRows = true,
// Source of data items.
ItemsSource = Inqueritos,
ItemTemplate = new DataTemplate(() => {
// Create views with bindings for displaying each property.
Label perguntaLabel = new Label();
Label respostaLabel = new Label();
Label respostaLabel1 = new Label();
Label respostaLabel2 = new Label();
var command = new Command(() => Debug.WriteLine("Command executed"));
var button = new Button
{
Text = "Open Inquery",
Command = doesnt find the GetinqueritoCommand,
};
respostaLabel.VerticalTextAlignment = TextAlignment.Center;
respostaLabel1.VerticalTextAlignment = TextAlignment.Center;
respostaLabel2.VerticalTextAlignment = TextAlignment.Center;
perguntaLabel.SetBinding(Label.TextProperty, "Pergunta");
respostaLabel.SetBinding(Label.TextProperty, "Resposta");
respostaLabel1.SetBinding(Label.TextProperty, "Resposta1");
respostaLabel2.SetBinding(Label.TextProperty, "Resposta2");
var cb = new Messier16.Forms.Controls.Checkbox() { IsEnabled = true };
var cb1 = new Messier16.Forms.Controls.Checkbox() {IsEnabled = true };
var cb2 = new Messier16.Forms.Controls.Checkbox() { IsEnabled = true };
return new ViewCell
{
View = new StackLayout
{
Children = {
new StackLayout {
Children = {
perguntaLabel,
},
},
new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children =
{
cb
}
},
new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children =
{
cb1
}
},
new StackLayout
{
Orientation = StackOrientation.Horizontal,
Children =
{
cb2
}
}
}
}
};
})
};
// Accomodate iPhone status bar.
this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
// Build the page.
this.Content = new StackLayout
{
BindingContext = new ViewModels.InqueritoViewModel(),
Children = {
listView,
}
};
}
}
以下是C#中用于设计的代码:
{{1}}
答案 0 :(得分:1)
button.SetBinding(Button.CommandProperty, "GetinqueritoCommand");