如何仅在 Xamarin 窗体 XAML 中设置左边距



这个问题与如何在 XAML 中设置上边距相同?但关于 Xamarin 而不是 WPF。

如何在 XAML 的视图上设置单个边距?

链接的问答指示默认实现始终将所有未指定的边距设置为 0,即使来自代码也是如此。

除非我遗漏了什么,否则只需指定边距,如下所示:

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

边距指定为值。

解决方案是创建一个 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

也许尝试一个 valueConverter,您可以在其中通过绑定将值发送到转换器并返回一个 Thickness 对象。有点像

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

你传递一个字符串并取回一个厚度对象的地方,例如 new thickness(0,marginleft,0,0) .

您也可以直接绑定到视图模型中的厚度类型对象,但这是一种不好的做法,因为它会在视图模型中创建一个视图依赖项,这违背了 MVVM 的目的

最新更新