这节讲 绑定与MVVM,直接上官网示例
两个Label属性都绑定到同页的Slider 的Value上。
上面那个会实时旋转,下面那个会实时变动字符串,
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XamlSamples.SliderBindingsPage"
Title="Slider Bindings Page">
<StackLayout>
<Label Text="ROTATION"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Slider x:Name="slider"
Maximum="360"
VerticalOptions="CenterAndExpand" />
<Label BindingContext="{x:Reference slider}"
Text="{Binding Value, StringFormat='The angle is {0:F0} degrees'}"
FontAttributes="Bold"
FontSize="Large"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage>
或者将多个属性绑定到一个控件上:注意看源控件(x:Name="label")被绑定的地方
是通过Slider上吧Binding Mode属性设为OneWayToSource或者TwoWay。
直接从其他控件去绑定和更改label的值。
顺便列举一下Binding Mode的枚举(哪个是源?值属于谁,谁就是源)
Default
OneWay
— 值从源传输到目标OneWayToSource
— 值从目标转移到源TwoWay
— 值在源和目标之间双向传输OneTime
— 数据从源到目标,但仅在BindingContext
发生变化时
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MVVMdemo.MainPage">
<Grid>
<Grid.RowDefinition