簡體   English   中英

如何僅在Xamarin Forms XAML中設置左邊距?

[英]How to set a left margin only in Xamarin Forms XAML?

此問題與如何僅在XAML中設置上邊距相同 但關於Xamarin而不是WPF。

如何在XAML的視圖上設置單個邊距?

鏈接的Q&A表示默認實現始終將所有未指定的邊距設置為0,即使是代碼也是如此。

解決方案是創建一個AttachedProperty

using System;
using Xamarin.Forms;
namespace Sample.Utils
{
    /// <summary>
    /// Allows setting Top,Left,Right,Bottom Margin independently from each other.
    /// The default implementation does not allow that, even from code. This
    /// attached property remembers the previously set margins and only modifies what you intend to modify.
    /// </summary>
    public static class Margin
    {
        public static readonly BindableProperty LeftProperty = BindableProperty.CreateAttached(
            propertyName: "Left",
            returnType: typeof(double),
            declaringType: typeof(Margin),
            propertyChanged: LeftPropertyChanged,
            defaultValue: 0.0d);

        private static void LeftPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            SetLeft(bindable, (double)newValue);
        }

        public static void SetLeft(BindableObject element, double value)
        {
            var view = element as View;
            if (view != null)
            {
                Thickness currentMargin = (Xamarin.Forms.Thickness)view.GetValue(View.MarginProperty);

                view.Margin = new Thickness(value, currentMargin.Top, currentMargin.Right, currentMargin.Bottom);
            }
        }

        public static double GetLeft(BindableObject element)
        {
            View view = element as View;
            if (view != null)
            {
                Thickness margin = (Xamarin.Forms.Thickness)view.GetValue(View.MarginProperty);
                return margin.Left;
            }
            return (double)LeftProperty.DefaultValue;
        }

    }
}

以相同的方式為BottomTopRight聲明這一點。 然后在XAML中使用它,如下所示:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
         xmlns:utils="using:Sample.Utils"
         x:Class="Sample.MyContentPage">
<StackLayout
   Orientation="Vertical"
   utils:Margin.Left="{StaticResource InnerPageContentMarginLeft}">
</StackLayout>
</ContentPage>

資料來源:
* https://forums.xamarin.com/discussion/66026/use-attached-bindable-property-in-xaml
* https://stackoverflow.com/a/32408461/2550406

除非我遺漏了什么,否則只需指定保證金如下:

<Label
    Margin = "0,20,0,0"
    Text = "Hello World!" />

保證金指定為值。

也許嘗試一個valueConverter,你可以通過綁定向轉換器發送一個值並返回一個Thickness對象。 有點像

Margin ={{Binding Marginleft, Converter={StaticResource stringToThicknessConverter}}

你傳遞一個字符串並返回一個厚度對象,如new thickness(0,marginleft,0,0)

你也可以直接綁定到viewModel中的厚度類型對象,但這是一個不好的做法,因為它會在ViewModel中創建一個View依賴,這違背了MVVM的目的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM