【问题标题】:Access custom control from ControlTemplate in current ContentPage从当前 ContentPage 中的 ControlTemplate 访问自定义控件
【发布时间】:2017-01-09 01:36:16
【问题描述】:

我想在我使用的每个页面上包含一个带有ActivityIndicator 的视图。因此,我创建了一个自定义控件和一个绝对/相对布局,如果你想让它全屏显示,这是必要的。其他解决方案在每个页面上嵌入ActivitIndicator。我正在寻找可以“自动”执行此操作的解决方案。

子类化是一种选择,但我希望在 XAML 中尽可能多地使用,这是我当前的解决方案无法提供的(而且结构模糊)。

现在我找到了ControlTemplate,并将我的自定义视图/控件放在那里。但是我看到我无法从ContentPage 访问自定义控件。有TemplateBinding,您可以在其中访问公共属性。例如。您可以更改标签的文本值。但我的情况有点复杂,我需要从文件/模型后面的代码访问控件。然后我可以打电话给show()hide()

How to access the elements of a ControlTemplate in Xamarin Forms 中有人提议使用命令,但这似乎只适用于少数控件(例如按钮)而不是我的自定义控件。

我能做什么?我可以做类似this.ControlTemplate.GetControl(controlName) 的事情吗?

【问题讨论】:

  • 我认为对于稍微复杂一点的情况,您可以使用自定义控件,您可以在自定义控件中声明可绑定属性、命令、事件并管理您想要的页面你把你的自定义控件。
  • 这听起来不错,但是如何访问自定义控件?仅在ControlTemplate中定义,页面上没有对其的引用。
  • 改写:您可以使用自定义控件 代替 ControlTemplate如何访问自定义控件? - 按名称 x:Name=""
  • 我编辑了我的问题以提供更多详细信息。我还想包括一些布局的东西,所以我认为自定义控件不能做到这一点。
  • 你想在每个页面上都有ActivityIndicator,而不是在每个页面上声明它吗?

标签: xaml xamarin xamarin.forms


【解决方案1】:

回到我对自定义控件的建议:

public partial class CustomActivityIndicator : Grid
{
    public static readonly BindableProperty IsBusyProperty =
        BindableProperty.Create(nameof(IsBusy),
                                typeof(bool),
                                typeof(CustomActivityIndicator),
                                default(bool));

    public bool IsBusy
    {
        get { return (bool)GetValue(IsBusyProperty); }
        set { SetValue(IsBusyProperty, value); }
    }

    public CustomActivityIndicator()
    {
        InitializeComponent();
    }
}

XAML:

<Grid x:Name="control"
      xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      x:Class="SuperForms.Samples.CustomActivityIndicator">
    <ActivityIndicator IsRunning="{Binding IsBusy, Source={x:Reference control}}"/>
</Grid>

使用方法:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SuperForms.Samples;assembly=SuperForms.Samples"
             x:Class="SuperForms.Samples.PageWithCustomActivityIndicator">
    <local:CustomActivityIndicator IsBusy="true"/>
</ContentPage>

【讨论】:

    【解决方案2】:

    我知道为什么...

    例如,如果您的自定义控件是

    public class LibraryGridView : View
    {
        public LibraryGridView()
        {
    
        }
    }
    

    那么你必须使用:

    LibraryGridView hebrewFlowLayout = (LibraryGridView)XFVisualTreeHelper.FindTemplateElementByName<View>(this, "MyLayoutElement");
    

    注意LibraryGridView&lt;View&gt; 的转换。

    【讨论】:

      猜你喜欢
      • 2013-10-07
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多