Xamarin表单-如何基于可见属性更改生成事件

时间:2019-06-28 23:13:15

标签: xamarin xamarin.forms

在我的应用程序中,某些ContentView在可见时需要采取措施(即加载其数据)。系统中有多个事件可以使它们变得可见,因此将装入数据操作与那些事件联系在一起是有问题的,因为其中许多事件可能一个接一个地发生。如果我有办法在Visible属性变为“ true”时简单地加载数据,那么我会处在更好的位置。

我创建了一个简单的示例以说明要完成的工作。也就是说,当Visible属性更改时,我需要ContentView生成事件。它不起作用,但是我认为它已经接近了,我希望有人向我展示如何使其工作。如果我可以使该示例正常工作,则可以将需要此功能的所有ContentView包装在提供所需事件的基本ContentView中。

所有代码都可以在GitHub here上找到。如果有帮助,您可以下载代码以查看整个解决方案。

首先,我定义了一个PanelView控件。注意,我在后面的代码中将IsVisible属性绑定到PanelVisible属性。

enter image description here

然后在后面的代码中,我有两个BindableProperty道具PanelVisibleProperty和ShowingProperty。 PanelVisible从上面绑定到IsVisible。关于propertyChanged事件,我正在调用“显示命令”。

enter image description here

在MainPage.xaml中,我有一个按钮,单击该按钮会调用ShowPanelView命令,该命令将设置PanelViewVisible属性并显示PanelView(在加载时最初隐藏)。并且,我将显示命令从PanelView绑定到模型中的PanelShowing命令。

enter image description here

最后,这是绑定到页面的MainPageModel ...

enter image description here

我没有在这里发生propertyChanged事件,如果我能做到这一点,那么我认为其余的工作都很好。

enter image description here

任何人都可以看到问题所在吗?非常感谢!

2 个答案:

答案 0 :(得分:0)

问题是当您更改 PanelViewVisible 值时,但未收到更改通知。要解决此问题,您必须对模型类实施 INotifyPropertyChanged

以下是代码:

  public class MainPageModel : FreshBasePageModel,INotifyPropertyChanged
  {
    public event PropertyChangedEventHandler PropertyChanged;

    public Command ShowPanelView
    {
        get
        {
            return new Command(() =>
            {
                PanelViewVisible = true;
            });
        }
    }
    bool _panelViewVisible;
    public bool PanelViewVisible
    {
        set { SetProperty(ref _panelViewVisible, value); }
        get { return _panelViewVisible; }
    }

    public Command PanelShowing
    {
        get
        {
            return new Command(() =>
            {
            });
        }
    }

    bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (Object.Equals(storage, value))
            return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

只需更换模型并检查。

答案 1 :(得分:0)

我发现了问题。在MainPage.xaml中,我绑定到PanelView的IsVisible属性。相反,它需要绑定到PanelVisible属性。现在一切正常。

这是MainPage.xaml的更新代码。并且我已经更新了GitHub repo,以防其他人有类似的需求。

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:PanelViewControl"
             x:Class="PanelViewControl.MainPage">

    <StackLayout Margin="100">
        <Button Text="Show Panel View Control" Command="{Binding ShowPanelView}" />
        <local:PanelView PanelVisible="{Binding PanelViewVisible}" 
                         Showing="{Binding PanelShowing}">
        </local:PanelView>
    </StackLayout>

</ContentPage>