Xamarin.Forms:XAML属性传递

时间:2018-03-15 16:52:49

标签: xamarin.forms inotifypropertychanged

如何在不编写代码的情况下将属性值传递给自定义控件子项?

内容页面:

<views:ButtonView Image="newViolationSmall.png" Text="{Binding ParentsText}/>

然后ButtonView.xaml

<StackLayout 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="SmartwebsCrossPlatform.Portable.Views.ButtonView">

    <Button Image="{Binding Image}"/>
    <Label Text="{Binding Text}" />

</StackLayout>

和ButtonView.cs

public partial class ButtonView : StackLayout {

...

    //text
    public static readonly BindableProperty TextProperty = BindableProperty.Create( "Text", typeof( string ), typeof( ButtonView ), null, BindingMode.Default, null, null, null, null );
    public string Text {
        get {
            return (string)GetValue( TextProperty );
        }
        set {
            SetValue( TextProperty, value );
        }
    }

    //image
    public static readonly BindableProperty ImageProperty = BindableProperty.Create( "Image", typeof( string ), typeof( ButtonView ) );
    public string Image {
        get {
            return (string)GetValue( ImageProperty );
        }
        set {
            SetValue( ImageProperty, value );
        }
    }

这不会显示任何文字或图片。一个相当烦人的选择是命名Button和Label,覆盖ButtonView.OnPropertyChanged,并从代码中显式设置它们的属性,但它导致System.ObjectDisposedException(对象名称:&#39; Android.Graphics.Bitmap&#39;)当我浏览此页面。

@ yyou的解决方案适用于const值,但不适用于父级属性。

1 个答案:

答案 0 :(得分:1)

唯一缺少的是设置此自定义布局的BindingContext。 即

   //ButtonView.xaml.cs
        public ButtonView ()
        {
            InitializeComponent ();
            BindingContext = this;
        }

    //to use this ButtonView component in a page
    //ie. DetailPage.xaml
    <ContentPage  ...>

        <app2:ButtonView Text="{Binding ParentText}" Image="{Binding ButtonImage }"/>

    </ContentPage>

//in DetailPage.xaml.cs
    public DetailPage() {
        InitializeComponent ();
        BindingContext = new DetailViewModel() {
                ParentText = "sjldfdkfdjd",
                ButtonImage = "my-button-image.png"
        };
    }

    //in the file DetailViewModel.cs
    namespace App2.ViewModels
    {
        public class DetailViewModel : BaseViewModel {
            private string _parentText;
            public string ParentText {
                get { return _parentText; }
                set { SetProperty<string>(ref _parentText, value); }
            }

        private string _buttonImage;
        public string ButtonImage {
            get { return _buttonImage; }
            set { SetProperty<string>(ref _buttonImage, value); }
        }

        //other stuff
    }
}