Xamarin Forms Make Button подходит для сетки - PullRequest
0 голосов
/ 29 октября 2019

У меня есть сетка только с 1 столбцом, и я хочу, чтобы моя кнопка соответствовала размеру сетки, я пытался использовать StackLayout, и Frame, теперь я пытаюсь с сеткой, также пытался с 1 столбцом и с 1 строкой,но результат тот же, я приложу фото, чтобы показать, что происходит:

enter image description here

Мне нужны красные кнопки, чтобы растянуть, чтобы они заполнилиширину устройства, я пробовал со свойствами StartAndExpand, Fill и FillAndExpand в горизонтальных опциях, но они не работают. с помощью Fill и FillAndExpand это работает, но текст кнопки перемещается в центр, а затем возникает ошибка, при которой каждый раз, когда я нажимаю на строку, текст перемещается влево и остается там, пока я не прокручиваю представление списка вниз и снова не возвращаю верхнюю часть.

Вот мой код:

<ListView x:Name="GroupsList"
                  ItemsSource="{Binding Dishes}"
                  IsGroupingEnabled="True"
                  SeparatorColor="Black"
                  SeparatorVisibility="Default"
                  HasUnevenRows="True">
            <ListView.Behaviors>
                <behaviorsPack:SelectedItemBehavior Command="{Binding BindingContext.SelectedDishCommand, Source={x:Reference DishesPage}}"></behaviorsPack:SelectedItemBehavior>
            </ListView.Behaviors>
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell Height="50">
                        <Grid VerticalOptions="FillAndExpand"
                                     BackgroundColor="LightSlateGray">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <Button BackgroundColor="DarkRed"
                                    Grid.Column="0"
                                    BorderColor="Transparent"
                                    BorderWidth="0"
                                    Text="{Binding Key}"
                                    TextColor="White"
                                    HorizontalOptions="StartAndExpand"
                                    Command="{Binding BindingContext.SelectGroupHeader, Source={x:Reference DishesPage}}"
                                    CommandParameter="{Binding Key}"
                                    ImageSource="next_disclosure"
                                    ContentLayout="Right"></Button>
                        </Grid>
                    </ViewCell>
            </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ContentView Padding="2, 5, 5, 0">
                            <Frame Padding="2"
                                   HasShadow="False"
                                   BackgroundColor="White">
                                <StackLayout Orientation="Horizontal">
                                    <Label Margin="10"
                                           Text="{Binding Name}"
                                           TextColor="Black"
                                           FontSize="Medium"
                                           HorizontalOptions="StartAndExpand"></Label>
                                </StackLayout>
                            </Frame>
                        </ContentView>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Надеюсь, кто-нибудь может мне помочь, пожалуйста.

1 Ответ

0 голосов
/ 29 октября 2019

Вы имеете в виду, что хотите, чтобы кнопка занимала всю ширину, а текст кнопки выравнивался по левому краю, если да, вы можете настроить кнопку и использовать CustomRenderer для ее достижения.

custom Кнопка :

public class ExtendedButton:Button
{
    public static BindableProperty HorizontalTextAlignmentProperty = BindableProperty.Create<ExtendedButton, Xamarin.Forms.TextAlignment>(x => x.HorizontalTextAlignment, Xamarin.Forms.TextAlignment.Center);
    public Xamarin.Forms.TextAlignment HorizontalTextAlignment
    {
        get
        {
            return (Xamarin.Forms.TextAlignment)GetValue(HorizontalTextAlignmentProperty);
        }
        set
        {
            SetValue(HorizontalTextAlignmentProperty, value);
        }
    }
}

, затем в Android.Project , пользовательский рендерер, например:

[assembly: ExportRenderer(typeof(ExtendedButton), typeof(ExtendedButtonRenderer))]
namespace App18.Droid
{
  public class ExtendedButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
  {

    public ExtendedButtonRenderer(Context context) : base(context)
    {
    }

    public new ExtendedButton Element
    {
        get
        {
            return (ExtendedButton)base.Element;
        }
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement == null)
        {
            return;
        }

        SetTextAlignment();
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == ExtendedButton.HorizontalTextAlignmentProperty.PropertyName)
        {
            SetTextAlignment();
        }
    }

    public void SetTextAlignment()
    {
        Control.Gravity = Element.HorizontalTextAlignment.ToHorizontalGravityFlags();
    }
}

 public static class AlignmentHelper
 {
    public static GravityFlags ToHorizontalGravityFlags(this Xamarin.Forms.TextAlignment alignment)
    {
        if (alignment == Xamarin.Forms.TextAlignment.Center)
            return GravityFlags.AxisSpecified;
        return alignment == Xamarin.Forms.TextAlignment.End ? GravityFlags.Right|GravityFlags.CenterVertical : GravityFlags.Left|GravityFlags.CenterVertical;
    }
  }
}

, наконец, в axml вашей страницы:

<ListView.GroupHeaderTemplate>
            <DataTemplate>
                <ViewCell Height="50">
                    <Grid VerticalOptions="FillAndExpand"
                                 BackgroundColor="LightSlateGray">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <local:ExtendedButton BackgroundColor="DarkRed"
                                Grid.Column="0"
                                BorderColor="Transparent"
                                BorderWidth="0"
                                Text="{Binding Key}"
                                TextColor="White"
                                HorizontalTextAlignment="Start" 
                                HorizontalOptions="FillAndExpand"
                                Command="{Binding BindingContext.SelectGroupHeader, Source={x:Reference DishesPage}}"
                                CommandParameter="{Binding Key}"
                                ImageSource="next_disclosure"
                                ContentLayout="Right"></local:ExtendedButton>
                    </Grid>
                </ViewCell>
        </DataTemplate>
</ListView.GroupHeaderTemplate>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...