将命令传递给ContentView中的按钮
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将命令传递给ContentView中的按钮相关的知识,希望对你有一定的参考价值。
我有一个ContentView
,在网格内有一个按钮。我为按钮和命令上的文本值设置了可绑定属性。文本值设置正确,但按钮设置不正确?我不明白这里发生了什么。有人有见识吗?
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Class="Aboo.Components.BusyButton"
BindingContext="{Binding Source={RelativeSource Self}}">
<ContentView.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="Button" Text="{Binding Text}" Command="{Binding Command}" Grid.ColumnSpan="3" />
<ActivityIndicator Grid.Column="1" IsRunning="{Binding IsBusy}" Color="White"/>
</Grid>
</ContentView.Content>
</ContentView>
和隐藏代码:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class BusyButton : ContentView
{
public BusyButton()
{
InitializeComponent();
}
public static readonly BindableProperty TextProperty =
BindableProperty.Create("Text", typeof(string), typeof(BusyButton), default(string));
public string Text
{
get => (string) GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly BindableProperty CommandProperty =
BindableProperty.Create("Command", typeof(ICommand), typeof(BusyButton), default(ICommand));
public ICommand Command
{
get => (ICommand) GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public static readonly BindableProperty IsBusyProperty =
BindableProperty.Create("IsBusy", typeof(bool), typeof(BusyButton), default(bool), propertyChanged: IsBusyChanged);
private static void IsBusyChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var busyButton = bindable as BusyButton;
if (busyButton == null)
return;
busyButton.Button.IsEnabled = !(bool) newvalue;
}
public bool IsBusy
{
get => (bool) GetValue(IsBusyProperty);
set => SetValue(IsBusyProperty, value);
}
}
使用这样的按钮:
答案
请删除此行的BindingContext="{Binding Source={RelativeSource Self}}"
。
在Content.BindingContext = this;
构造函数中添加BusyButton
。根据我的测试,BindingContext="{Binding Source={RelativeSource Self}}"
在嵌套绑定中不起作用。
请在x:Name="MyButton"
中为Button
添加名称ContentView
,然后在IsBusyChanged
方法中更改按钮名称。
以上是关于将命令传递给ContentView中的按钮的主要内容,如果未能解决你的问题,请参考以下文章