BindingContext在Xamarin表单中不起作用

时间:2017-04-23 07:41:07

标签: c# xaml xamarin xamarin.android xamarin.forms

我使用下面的代码将数据绑定到标签以更改滑块值,并且工作正常。

 <StackLayout VerticalOptions="Center" HorizontalOptions="Center" >
    <Label Text="{Binding Source={x:Reference slider1}, Path=Value, StringFormat='Value is {0:F2}'}"
           Opacity="{Binding Source={x:Reference slider1}, Path=Value}"
           x:Name="label1"/>
    <Slider x:Name="slider1"></Slider>
 </StackLayout>

xaml.cs 页面中,我已将滑块值启动为0.5

   public MainPage()
   {
       InitializeComponent();
       slider1.Value=0.5;
   }

enter image description here

但是,当我想使用 BindingContext 绑定数据时,它不能正确显示输出。

<StackLayout VerticalOptions="Center" HorizontalOptions="Center" >
    <Label BindingContext="x:Reference slider1" 
           Text="{Binding Value, StringFormat='Value is {0:F2}'}"
           Opacity="{Binding Value}"
           x:Name="label1"/>
    <Slider x:Name="slider1"></Slider>
 </StackLayout>

enter image description here

我的第二个xaml有什么问题?

2 个答案:

答案 0 :(得分:1)

我想,你错过了{}。试试

13.0
6
1       SQLCHAR             0       255     ","      1     SERIES_NAME                      SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR             0       1       ","      2     ONGOING_SERIES                   ""
3       SQLCHAR             0       11      ","      3     RUN_START                        ""
4       SQLCHAR             0       11      ","      4     RUN_END                          ""
5       SQLCHAR             0       510     ","      5     MAIN_CHARACTER                   SQL_Latin1_General_CP1_CI_AS
6       SQLCHAR             0       510     "\r\n"   6     PUBLISHER                        SQL_Latin1_General_CP1_CI_AS

而不是

<Label BindingContext="{x:Reference slider1}"

答案 1 :(得分:0)

如果您使用BindingContext,则该对象应实现INotifyPropertyChanged

Slider没有实现此接口。通常,您应该将BindableProperty分配给BindingContext

https://developer.xamarin.com/guides/xamarin-forms/xaml/bindable-properties/