将命令传递给ContentView中的按钮

问题描述 投票:0回答:1

我有一个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);
    }
}

使用这样的按钮:

xamarin.forms
1个回答
0
投票

请删除此行的BindingContext="{Binding Source={RelativeSource Self}}"

Content.BindingContext = this;构造函数中添加BusyButton。根据我的测试,BindingContext="{Binding Source={RelativeSource Self}}"在嵌套绑定中不起作用。

请在x:Name="MyButton"中为Button添加名称ContentView,然后在IsBusyChanged方法中更改按钮名称。

© www.soinside.com 2019 - 2024. All rights reserved.