【问题标题】:View IsEnabled Property is not working on Xamarin Forms查看 IsEnabled 属性不适用于 Xamarin 窗体
【发布时间】:2022-01-20 02:19:28
【问题描述】:

这是我的列表视图 里面的 Listview 按钮 IsEnabled 属性不起作用,IsEnabled False 不起作用。 我按照此步骤操作但仍然无法正常工作 https://forums.xamarin.com/discussion/47857/setting-buttons-isenabled-to-false-does-not-disable-button 在我的 ViewModel 中

OrderItems=PopuldateOrders();// getting List Items

<ListView x:Name="OrderItems" VerticalOptions="Fill" 
                                  BackgroundColor="White" HasUnevenRows="True" 
                                  SeparatorVisibility="None" ItemsSource="{Binding OrderItems}">
                            <ListView.ItemTemplate>
                                <DataTemplate>
                                    <ViewCell>
                                        <ContentView BackgroundColor="White">
                                            <Grid BackgroundColor="Transparent" Margin="0" VerticalOptions="FillAndExpand" x:Name="Item">
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="*" />
                                                </Grid.RowDefinitions>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition Width="10*"/>
                                                    <ColumnDefinition Width="18*"/>
                                                    <ColumnDefinition Width="18*"/>
                                                    <ColumnDefinition Width="17*"/>
                                                    <ColumnDefinition Width="20*"/>
                                                    <ColumnDefinition Width="17*"/>
                                                </Grid.ColumnDefinitions>
                                                <Label Text="{Binding PullSheetId}" Grid.Row="0" IsVisible="False"/>
                                                <controls:CheckBox Checked="{Binding IsChecked}" Grid.Row="0" Grid.Column="0" IsVisible="{Binding IsEnableShipBtn}" Scale=".8"/>
                                                <Label Text="{Binding KitSKU}" Grid.Row="0" Grid.Column="1" 
                                                   HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="Black"/>
                                                <Label Text="{Binding SKU}" Grid.Row="0" Grid.Column="2" 
                                                   HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="{Binding ItemColor}"/>
                                                <Label Text="{Binding ReqPackQty}" Grid.Row="0" Grid.Column="3" 
                                                   HorizontalTextAlignment="Center" VerticalOptions="Center" FontSize="Small" TextColor="Black"/>
                                                <local:EntryStyle Scale=".6" Text="{Binding ScanQuantity}" Grid.Row="0" Keyboard="Numeric"
                                                                  Grid.Column="4" HorizontalTextAlignment="Center" 
                                                                  VerticalOptions="Center" Placeholder="Qty" IsEnabled="True" x:Name="QtyEntry"
                                                                  >
                                                    <local:EntryStyle.Behaviors>
                                                        <eventToCommand:EventToCommandBehavior EventName="TextChanged"  
                                                                                               Command="{Binding Source={x:Reference OrderItems}, Path=BindingContext.ChangeItemQty}"
                                                                                                CommandParameter="{Binding Source={x:Reference Item}, Path=BindingContext}"
                                                                                               />
                                                    </local:EntryStyle.Behaviors>
                                                </local:EntryStyle>
                                                <Button Text="Ship" Scale=".6" Grid.Row="0" Grid.Column="5"  
                                                    VerticalOptions="Center" BackgroundColor="#6eb43a" TextColor="White" 
                                                    BorderRadius="20" CornerRadius="20" BorderColor="{Binding isError}" BorderWidth="3" 
                                                    MinimumWidthRequest="60"
                                                        x:Name="ShipBtn" 
                                                        Command="{Binding Source={x:Reference OrderItems}, Path=BindingContext.SubmitSingleItem}" 
                                                        IsEnabled="{Binding IsEnableShipBtn}" IsVisible="{Binding IsEnableShipBtn}"
                                                        CommandParameter="{Binding .}" 
                                                        />

                                            </Grid>
                                        </ContentView>
                                    </ViewCell>
                                </DataTemplate>
                            </ListView.ItemTemplate>
                            <ListView.Behaviors>
                                <eventToCommand:EventToCommandBehavior EventName="ItemTapped" Command="{Binding PackerItemsItemTapped}"/>
                            </ListView.Behaviors>
                        </ListView>

如何解决?

【问题讨论】:

标签: xamarin xamarin.forms


【解决方案1】:

您可以在ICommand 中实现CanExecute 方法来替换Button 的IsEnabled 属性。你可以参考我的demo。

这是我演示的 GIF。

首先,您可以看到 MainPage.xaml。为按钮绑定模型视图和设置命令。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:TestDemo"
         x:Class="TestDemo.MainPage">
<!--BindingContext from  ButtonExecuteViewModel -->
<StackLayout>
    <StackLayout.BindingContext>
       <local:ButtonExecuteViewModel/>
    </StackLayout.BindingContext>

    <Button
         Text="click me to enable following button"
         Command="{Binding NewCommand}"/>

    <Button
         Text="Cancel"
         Command="{Binding CancelCommand}"/>

</StackLayout>

这里是视图模型 ButtonExecuteViewModel.cs。你可以看到ButtonExecuteViewModel的构造方法,它将executecanExecute设置为达到按钮的isEnable。

public class ButtonExecuteViewModel : INotifyPropertyChanged
{

    bool isEditing;
    public event PropertyChangedEventHandler PropertyChanged;
    public ButtonExecuteViewModel()
    {

        NewCommand = new Command(
            execute: () =>
            {

                IsEditing = true;
                RefreshCanExecutes();
            },
            canExecute: () =>
            {
                return !IsEditing;
            });



        CancelCommand = new Command(
            execute: () =>
            {
                IsEditing = false;
                RefreshCanExecutes();
            },
            canExecute: () =>
            {
                return IsEditing;
            });

    }
    void RefreshCanExecutes()
    {
        (NewCommand as Command).ChangeCanExecute();

        (CancelCommand as Command).ChangeCanExecute();
    }

    public ICommand NewCommand { private set; get; }

    public ICommand CancelCommand { private set; get; }

    public bool IsEditing
    {
        private set { SetProperty(ref isEditing, value); }
        get { return isEditing; }
    }
    //Determine if it can be executed
    bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

【讨论】:

    【解决方案2】:

    我在这里尝试了所有答案,但没有任何效果,我只解决了创建自定义按钮组件:

    • CustomButtonView.xaml
    <Button xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="CustomComponents.CustomButton.CustomButtonView"
            FontAttributes="Bold"
            TextColor="White"
            FontSize="20"
            TextTransform="Uppercase"
            CornerRadius="20"
            WidthRequest="200"
            HorizontalOptions="Center" />
    
    • CustomButtonView.xaml.cs:自定义IsEnabled 的魔力在这里
    using System.Windows.Input;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    namespace CustomComponents.CustomButton
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class CustomButtonView
        {
            #region constructors
    
            public CustomButtonView()
            {
                InitializeComponent();
                BackgroundColor = Color.Blue;
    
                Clicked += (_, args) =>
                {
                    if (IsEnabled) Command?.Execute(args);
                };
            }
    
            #endregion
    
            #region Command
    
            public new static readonly BindableProperty CommandProperty = BindableProperty.Create(
                nameof(Command),
                typeof(ICommand),
                typeof(CustomButtonView));
    
            public new ICommand? Command
            {
                get => (ICommand)GetValue(CommandProperty);
                set => SetValue(CommandProperty, value);
            }
    
    
            #endregion
            
            #region IsEnabled
    
            public new static readonly BindableProperty IsEnabledProperty = BindableProperty.Create(
                nameof(IsEnabled),
                typeof(bool),
                typeof(CustomButtonView),
                true,
                propertyChanged: (bindable, _, newValue) =>
                {
                    var component = (CustomButtonView)bindable;
    
                    if ((bool)newValue)
                    {
                        component.BackgroundColor = Color.Blue;
                    }
                    else
                    {
                        component.BackgroundColor = Color.Red;
                    }
                });
    
            public new bool IsEnabled
            {
                get => (bool)GetValue(IsEnabledProperty);
    
                set => SetValue(IsEnabledProperty, value);
            }
    
            #endregion
        }
    }
    

    现在您可以像使用 XAML 中的任何常规按钮一样使用它:

    <customButton:CustomButtonView Text="Button enabled"
       Command="{Binding SomeCommand}"
       IsEnabled="True"/>
    
    <customButton:CustomButtonView Text="Button disabled"
       Command="{Binding SomeCommand}"
       IsEnabled="False"/>
    

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 2023-03-03
      • 2016-07-29
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 2019-07-13
      • 2016-07-16
      • 2017-09-25
      相关资源
      最近更新 更多