【发布时间】:2019-04-16 09:06:20
【问题描述】:
这个问题与How to set a top margin only in XAML? 相同,但与 Xamarin 而不是 WPF 有关。
如何在 XAML 中的视图上设置单独的边距?
链接的问答表明默认实现始终将所有未指定的边距设置为 0,即使从代码中也是如此。
【问题讨论】:
标签: c# xaml xamarin.forms
这个问题与How to set a top margin only in XAML? 相同,但与 Xamarin 而不是 WPF 有关。
如何在 XAML 中的视图上设置单独的边距?
链接的问答表明默认实现始终将所有未指定的边距设置为 0,即使从代码中也是如此。
【问题讨论】:
标签: c# xaml xamarin.forms
解决办法是创建一个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;
}
}
}
以相同的方式声明 Bottom、Top 和 Right。然后像这样在 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
【讨论】:
除非我遗漏了什么,否则只需按如下方式指定 Margin:
<Label
Margin = "0,20,0,0"
Text = "Hello World!" />
Margin 指定为 left, top, right, bottom价值观。
【讨论】:
也许可以尝试使用 valueConverter,您可以在其中通过绑定将值发送到转换器并返回 Thickness 对象。 有点像
Margin ={{Binding Marginleft, Converter={StaticResource stringToThicknessConverter}}
您传递一个字符串并返回一个厚度对象,例如
new thickness(0,marginleft,0,0).
您也可以直接绑定到 viewModel 中的厚度类型对象,但这是一种不好的做法,因为它会在 ViewModel 中创建一个 View 依赖项,从而违背 MVVM 的目的
【讨论】: