【发布时间】:2018-11-21 14:26:19
【问题描述】:
有没有办法将网格的属性(行定义、列定义、行间距、列间距等)绑定到 ViewModel?
【问题讨论】:
有没有办法将网格的属性(行定义、列定义、行间距、列间距等)绑定到 ViewModel?
【问题讨论】:
查看源代码总是有帮助的:https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Grid.cs#L20
所以它看起来确实像 rowdefinitions、columndefintions、rowspacing、columnspacing 是可绑定的属性,如代码所示:
public static readonly BindableProperty RowSpacingProperty = BindableProperty.Create("RowSpacing", ...);
public static readonly BindableProperty ColumnSpacingProperty = BindableProperty.Create("ColumnSpacing", ...);
public static readonly BindableProperty ColumnDefinitionsProperty = BindableProperty.Create("ColumnDefinitions", ...);
public static readonly BindableProperty RowDefinitionsProperty = BindableProperty.Create("RowDefinitions", ...);
更新:所以这里是使这个绑定工作需要做的事情:
如果使用Bindings Value Converter,请确保它永远不会返回 null。
然后,通过将 Grid 的 TargetNullValue 和 FallbackValue 分配给空的 Row/ColumnDefinitionCollection(例如,使用 StaticResource)来防止任何绑定解析。
为此,首先在 App.xaml 中创建一个 static resource,它只是一个 Row/ColumnDefinitionCollection:
<Application.Resources>
<ResourceDictionary>
<RowDefinitionCollection x:Key="NullRowDefs" />
<ColumnDefinitionCollection x:Key="NullColDefs" />
</ResourceDictionary>
</Application.Resources>
然后将Grid的TargetNullValue和FallbackValue属性设置为上述静态资源:
<Grid RowDefinitions="{Binding RowSize, TargetNullValue={StaticResource NullRowDefs}, FallbackValue={StaticResource NullRowDefs}}"
ColumnDefinitions="{Binding ColumnSize, TargetNullValue={StaticResource NullColDefs}, FallbackValue={StaticResource NullColDefs}}"
x:Name="grid">
执行上述操作应该可以解决ArgumentException。
更新:此绑定应该在不提供TargetNullValue 和FallbackValue 的情况下工作。发现了 bug 并创建了 PR,因此应该在即将发布的版本中修复此问题,但与此同时,请使用解决方法。
【讨论】: