Xamarin - 绑定到ControlTemplate

时间:2017-01-30 22:25:58

标签: c# xamarin binding xamarin.forms controltemplate

我正在构建一个Xamarin.Forms移动应用程序,该应用程序将在用户使用该应用程序时播放音频文件。用户将能够在开始播放文件后继续使用该应用程序,并且该文件将通过静态类而不是单个视图播放/管理(因为该视图可能会在文件中从导航堆栈中删除还在上演。)

我希望有一个迷你播放器在应用内的任何其他视图中都可见,我正在使用ControlTemplate来完成此任务。我希望这个控件模板有一些绑定到静态类中的属性的项(例如播放器状态[播放/暂停],剩余时间,标题等),以及控制在静态类上运行方法。我可以在app.xaml页面(ControlTemplate所在的位置)中使用代码运行方法,但是我很难将绑定属性绑定。

现在我只有一个切换,其中IsToggled应绑定到可绑定属性IsPlaying绑定到静态类'bindable属性。

我继续收到以下错误:

Xamarin.Forms.Xaml.XamlParseException: Type AudioPlayer.Current not found in 
xmlns clr-namespace:AudioPlayerBar;assembly=AudioPlayerBar...

我在所有.xaml中都在XMLNS中定义了命名空间,所以我不确定是怎么回事。我的整个项目都在https://github.com/ChetCromer/XamarinPrototypes/tree/master/AudioPlayerBar

的GitHub上

这是我的静态类:

using System;
using System.ComponentModel;
using Xamarin.Forms;

namespace AudioPlayerBar
{
public  class AudioPlayer :INotifyPropertyChanged
{
    // Singleton for use throughout the app
    public static AudioPlayer Current = new AudioPlayer();

    //Don't allow creation of the class elsewhere in the app.
    private AudioPlayer()
    {
    }

    private bool _IsPlaying = false;

    //property for whether a file is being played or not
    public bool IsPlaying
    {
        get
        {
            return _IsPlaying;
        }
        set
        {
            _IsPlaying = value;
            OnPropertyChanged("IsPlaying");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged == null)
            return;

        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
}

这是我的ControlTemplate(在app.xaml里面)

<ControlTemplate x:Key="PlayerPageTemplate">
            <StackLayout VerticalOptions="FillAndExpand">
                <ContentView VerticalOptions="FillAndExpand">
                    <ContentPresenter />
                </ContentView>
                <StackLayout x:Name="stackFooterContent">
                    <Label Text="IsPlaying Value:"/>
                    <Switch IsToggled="{x:Static local:AudioPlayer.Current.IsPlaying}" />
                    <Button Text="Toggle IsPlaying" Clicked="Click_PlayPause" />
                </StackLayout>
            </StackLayout>
        </ControlTemplate>

有什么想法?我承认我是Xamarin中的新手,但我正在阅读的内容似乎更多地应用于ContentPages,并且它与ControlTemplates的工作方式不同。

1 个答案:

答案 0 :(得分:1)

我使用这里的示例工作:Binding to a property within a static class instance

这不是同一个问题所以我要离开我的问题并回答它。

我确实更改了我的课程以匹配上面的答案,但最大的变化是绑定代码在xaml中的外观:

//New 2 way bindable property I made up
<Label Text="{Binding Source={x:Static local:AudioPlayer.Instance},Path=Title}"/>

//Boolean bindable property
<Switch IsToggled="{Binding Source={x:Static local:AudioPlayer.Instance},Path=IsPlaying}" />

“路径”似乎是最大的区别。猜猜我现在正在阅读更多内容,因为它刚刚出现。