我试图将命令绑定到Xaml中的按钮。我可以绑定在ViewModel中声明的属性,并看到它来改变按钮背景的颜色。使用相同的方式将命令添加到按钮上,当我单击按钮时,按钮不会触发命令。
My ViewModel Command Property
public Color Color
{
get
{
return Color.Teal;
}
}
public ICommand OpenFileCommand = new Command((object obj) => {
Task.Run(() =>
{
var pickFileTask = CrossFilePicker.Current.PickFile();
var data = pickFileTask.Result;
//OpenDocument(data.FileName, data.DataArray);
});
});
Xaml部分:
<!-- Left Panel -->
<StackLayout x:Name="leftStack" Orientation="Vertical" BackgroundColor="Transparent">
<Button
x:Name="btnOpen"
BackgroundColor="{Binding Color}"
Command="{Binding OpenFileCommand}"
Image="addfile"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
WidthRequest="40"
HeightRequest="40">
</Button>
如果我在代码中绑定命令,它将在视图模型类中执行openfilecommand:
btnOpen.Command = viewModel.OpenFileCommand;
对我来说有效的是将iccommand定义为带有getter的属性:
public ICommand OpenFileCommand { get { return new Command(() => TestMethod()); } }
public void TestMethod() {
//Do stuff here
}
我通过改变视图模型类来定义命令属性。
public ICommand OpenFileCommand
{
get
{
return new Command((object obj) =>
{
Task.Run(() =>
{
var pickFileTask = CrossFilePicker.Current.PickFile();
var data = pickFileTask.Result;
OpenDocument(data.FileName, data.DataArray);
});
});
}
}