2017-03-21 34 views
2

我做了一个显示文本的自定义视图。Xamarin DataBinding bindableProperty(CustomView)

在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"/> 
其他页面

it会工作得很好。但是,当我一个数据绑定到该

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

那么它不会desplay什么...

它不是post.uploader.username值是错误的或一些这样的事情的问题。因为

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

我有这样的代码有权根据该故障线路,它只是正常工作太..

我到底做错了什么? 如何解决它..?

+0

你可能需要实现'PropertyChanged'功能让用户界面知道你的价值更新 –

+0

好吧,我会尝试。但这会解释为什么/// ///此工作和/// ///这不是?? – uzu

+0

因为将它设置为静态值只需设置一次,就是这样。在使用绑定时,值首先获取默认值(空),绑定发生时值会更新。因为你缺少属性改变的逻辑值永远不会更新在UI –

回答

0

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

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

BindableObject对象必须post属性对象,其中有uploader属性对象,其中有username属性字符串

+0

对不起。但那不回答我的问题 – uzu