如何绑定十进制值?

刻痕

我收到一个错误:

默认值与返回类型不匹配

参数名称:defaultValue

我创建了一个最小,完整和可验证的示例

CustomCell.cs:

class CustomCell : ViewCell
{
    private readonly Label _label;

    public static readonly BindableProperty DecimalDataProperty = BindableProperty.Create("DecimalData", typeof(decimal), typeof(CustomCell), "DecimalData");

    public decimal DecimalData
    {
        get { return (decimal)GetValue(DecimalDataProperty); }
        set { SetValue(DecimalDataProperty, value); }
    }

    public CustomCell()
    {
        _label = new Label { HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)) };

        _label.SetBinding(Label.TextProperty, new Binding(path: "DecimalData", stringFormat: "{0}"));


        var horizontalStack = new StackLayout
        {
            Orientation = StackOrientation.Horizontal,
            HeightRequest = 35,
            Padding = new Thickness(10, 0, 10, 0)
        };

        horizontalStack.Children.Add(_label);

        View = horizontalStack;
    }
}

Page1.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:app8="clr-namespace:App8;assembly=App8"
             x:Class="App8.Page1">
  <ListView x:Name="listView">
    <ListView.ItemTemplate>
      <DataTemplate>
        <app8:CustomCell DecimalData="{Binding DecimalData}" />
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

Page1.xaml.cs:

public class Model
{
    public decimal DecimalData { set; get; }
}
public partial class Page1 : ContentPage
{
    public Page1()
    {
        try
        {
            InitializeComponent();

            var list = new List<Model>
            {
                new Model {DecimalData = 565},
                new Model {DecimalData = 876},
                new Model {DecimalData = 123}
            };

            listView.ItemsSource = list;
        }
        catch (Exception ex)
        {
            
        }
    }
}

问题很简单:如何将十进制值绑定到自定义ViewCell?

可能是个错误吗?

克里斯·弗

Xamarin开发人员站点BindableProperty上列出的两个Create方法,第四个参数是该属性的默认值。

对于a,decimal它应该是一个数值(可能为0),但是您要再次传递属性名称(“ DecimalData”)。

0替换第二个“ DecimalData” (由于参数是一个对象,因此您必须更加明确)0m

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章