【问题标题】:Can't get access to controls from code behind in pcl part of xamarin forms project无法从 xamarin 表单项目的 pcl 部分中的代码访问控件
【发布时间】:2017-01-23 17:30:36
【问题描述】:

我有 Xamarin.Forms 项目,其中包含 pcl-part 和本机 win、ios 和 android 部分。 所有页面结构和视图模型都在 pcl 部分。应用程序工作正常,但是当我尝试例如从代码中隐藏 Grid 时 - 它什么也不做。这是代码示例:

Xaml

<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="SomeNamespase.SomePage">

    <Grid x:Name="InnerGrid" BackgroundColor="Green">
        <Frame x:Name="InnerContent"/>
    </Grid>
</ContentPage>

.cs

using System;

namespace SomeNamespase
{
    public partial class SomePage : ContentPage
    {
        public void SomeMethod()
        {
            this.InnerGrid.IsVisible = false;
            this.InnerContent.BackgroundColor = Color.Aqua;           
        }
    }
}

我也试过this.FindByName&lt;Grid&gt;("InnerGrid");同样的结果

注意:如果我想从 PCL 中的操作中获得控制,一切都很好。当我试图从 Windows(或其他平台)项目中的 ViewPresenter 获取控件时,什么也没有发生。

【问题讨论】:

  • 您是否尝试将 Grid 的可见性绑定到 ViewModel 中的属性?
  • 是的,很遗憾也没有帮助
  • 如果设置了断点,那几行代码会执行吗?
  • 是的,在调试模式下,代码正在运行所有行,但没有任何反应

标签: xaml xamarin xamarin.forms code-behind xforms


【解决方案1】:

您需要确保正确实施 INotifyPropertyChanged

protected virtual void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

【讨论】:

    【解决方案2】:

    请尝试以下代码,因为在您的代码中我看不到构造函数。

    using System;
    
    namespace SomeNamespase
    {
        public partial class SomePage : ContentPage
        {
            public SomePage() 
           {
                SomeMethod() ;
           } 
            public void SomeMethod()
            {
                this.InnerGrid.IsVisible = false;
                this.InnerContent.BackgroundColor = Color.Aqua;           
            }
        }
    } 
    

    【讨论】:

    • 对不起,没有完整的代码示例,构造函数在那边。但是方法不应该在构造函数中使用,而是在运行时使用,当我们使用接口实现的方法之一时
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2016-11-14
    • 2021-01-09
    • 2015-03-01
    • 1970-01-01
    相关资源
    最近更新 更多