【问题标题】:Xamarin DataBinding to bindableProperty (CustomView)Xamarin DataBinding 到 bindableProperty (CustomView)
【发布时间】:2017-08-13 04:54:49
【问题描述】:

我制作了一个显示文本的自定义视图。

在 TestView.xaml 中

<?xml version="1.0" encoding="UTF-8"?>
<ContentView 
    xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="EodiRoad.TestView">
    <StackLayout>

        <Label Text="{Binding Test}"/>
        <Label Text="this is test view"/>

    </StackLayout>
</ContentView>

和代码隐藏

在 TestView.xaml.cs 中

    public partial class TestView : ContentView
    {


        public static BindableProperty TestProperty =
            BindableProperty.Create(
                propertyName: "Test",
                returnType: typeof(string),
                declaringType: typeof(TestView),
                defaultValue:"???"
            );

        public string Test
        {
            get
            { return (string)GetValue(TestProperty); }
            set
            {
                Debug.WriteLine("test setted value = " + (string)value);
                SetValue(TestProperty, value); 
            }
        }



        public TestView()
        {
            InitializeComponent();
            BindingContext = this;
        }
    }

当我使用这个页面时是这样的

<local:TestView Test="hjhkhjk"/>

它会工作得很好。但是当我将数据绑定到它时

<local:TestView Test="{Binding post.uploader.username}"/>

那么它不会显示任何东西......

post.uploader.username 值错误或类似的事情不是问题。因为

<Label Text="{Binding post.uploader.username}"/>

我在故障线下面有这段代码,它也可以正常工作..

我在这里做错了什么? 如何解决它..?

【问题讨论】:

  • 您可能需要实现 PropertyChanged 功能,让 UI 知道您的值已更新
  • 好吧,我试试。但这能解释为什么 /// /// 这行得通和 /// /// /这不??
  • 因为将其设置为静态值只需设置一次即可。使用绑定时,值首先获取默认值(空),并且当绑定发生时,值会更新。因为您缺少属性更改逻辑,所以值永远不会在 UI 中更新
  • 如果多个 ui 元素在 TestView.xaml 中使用类似这样的一个属性会怎样 /// /// 我应该如何实现onpropertychanged like?

标签: c# xaml xamarin xamarin.forms


【解决方案1】:

您只能从 TestView 类中的 BindableObject 属性对象进行绑定。例如,如果你要写下一段代码:

<local:TestView Test="{Binding post.uploader.username}" />

您的BindableObject 对象必须具有post 属性对象,该对象具有uploader 属性对象,该对象具有username 属性字符串

【讨论】:

  • 对不起。但这并不能回答我的问题
猜你喜欢
  • 2020-07-21
  • 1970-01-01
  • 2017-12-27
  • 2017-02-14
  • 2018-10-21
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多