简体   繁体   English

在 contenview Xamarin.forms 中为 ColumnDefinitionCollection 创建可绑定属性

[英]Create bindable property for ColumnDefinitionCollection in contenview Xamarin.forms

I have a common ContentView which has been called in many ContentPages.我有一个在许多 ContentPages 中被调用的通用 ContentView。 Different pages have different requirements, according to the requirement, I want to change ColumnDefinition width property.不同的页面有不同的要求,根据要求,我想改变 ColumnDefinition 的宽度属性。

For Example:例如:

On one page, There are three controls inside the Grid view, and the widths are " ,1, "在一页上,Grid 视图内有三个控件,宽度分别为“ ,1,

<Grid ColumnDefinitions="*,1,*">

but on the other pages, I want to turn off the visibility of the first two controls, that is why I want to assign a width to Auto for the first two controls.但在其他页面上,我想关闭前两个控件的可见性,这就是为什么我想为前两个控件分配一个宽度给 Auto。

<Grid ColumnDefinitions="Auto,Auto,*">

In order to achieve this functionality, I have created bindable property.为了实现这个功能,我创建了可绑定属性。

public static readonly BindableProperty GridColumnDefinitionProperty =
            BindableProperty.Create(nameof(GridColumnDefinition), typeof(ColumnDefinitionCollection), typeof(PopupView), "*,1,*"); 

public ColumnDefinitionCollection GridColumnDefinition
        {
            get => (ColumnDefinitionCollection)GetValue(GridColumnDefinitionProperty);
            set => SetValue(GridColumnDefinitionProperty, value);
        }

but I am getting this error但我收到了这个错误

System.ArgumentException: 'Default value did not match return type. System.ArgumentException: '默认值与返回类型不匹配。 Property: Xamarin.Forms.ColumnDefinitionCollection PopupView.GridColumnDefinition Default value type: String, Parameter name: defaultValue'属性:Xamarin.Forms.ColumnDefinitionCollection PopupView.GridColumnDefinition 默认值类型:字符串,参数名称:defaultValue'

I am getting this error at the Bindable property line.我在 Bindable 属性行收到此错误。

For simple situations, an alternative approach is to create the needed ColumnDefinitions in code behind.对于简单的情况,另一种方法是在后面的代码中创建所需的 ColumnDefinitions。 With a bool property controlling when to do so.使用bool属性控制何时这样做。

<Grid x:Name="theGrid" ... />
public static readonly BindableProperty UseAutoColumnsProperty =
    BindableProperty.Create(nameof(UseAutoColumns), typeof(bool), typeof(ContentPage), false);
public bool UseAutoColumns
{
    get => (bool)GetValue(UseAutoColumnsProperty);
    set
    {
        SetValue(UseAutoColumnsProperty, value);

        if (value)
            theGrid.ColumnDefinitions = new ColumnDefinitionCollection
            {
                new ColumnDefinition(GridLength.Auto),
                new ColumnDefinition(GridLength.Auto),
                new ColumnDefinition(GridLength.Star),
            };
    }
}


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM