xamarin形式:如何使用步进器更改标签

时间:2018-10-22 13:39:49

标签: xamarin.forms

我想根据步进值的变化来增加或减少标签的值,但是卡在这里。这是我的代码

<ListView x:Name="mylistview"


  >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>

                <StackLayout HorizontalOptions="StartAndExpand">

                    <Label HorizontalOptions="Center"   Text="{Binding Qty, StringFormat='Qty. {0:N}'}" FontSize="11"
                   TextColor="Black" />

                    <Stepper ValueChanged="stepper_ValueChanged"   Minimum="0" Maximum="10" x:Name="stepper" Value="{Binding Qty}" Increment="0.1" HorizontalOptions="LayoutOptions.Center" VerticalOptions="LayoutOptions.CenterAndExpand"  />

                </StackLayout>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

2 个答案:

答案 0 :(得分:0)

如果使用的是MVVM,请按照以下步骤操作

  1. 具有Label的模型属性(引发属性更改的事件处理程序),该属性显示计数。
  2. 在stepper_ValueChanged中,获取与该视图单元格关联的对象(模型数据),然后在视图模型中对其进行编码,以基于值更改来设置/更改标签的count属性。

答案 1 :(得分:0)

1。在代码中,如果您只想将标签文本绑定到步进,则可以执行此操作。

<ListView x:Name="mylistview">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>

            <StackLayout HorizontalOptions="StartAndExpand">

                <Label HorizontalOptions="Center" BindingContext="{x:Refrence Name=stepper}"  Text="{Binding Path=Value, StringFormat='Qty. {0:N}'}" FontSize="11"
               TextColor="Black" />

                <Stepper ValueChanged="stepper_ValueChanged"   Minimum="0" Maximum="10" x:Name="stepper" Increment="0.1" HorizontalOptions="LayoutOptions.Center" VerticalOptions="LayoutOptions.CenterAndExpand"  />

            </StackLayout>

        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

只需在标签上添加bindcontext,然后绑定stepper的值,该标签文本就可以被stepper更改。如果有问题,可以参考这里official document

2,使用模型绑定数据时,应使用INotifyPropertyChanged到您的模型,如果没有,则无法更改该值。

3,当您使用模型时,根据您的代码,数量应包含在列表视图的项目源中,而不是仅包含在BindContext中,因此数量可以有用。