关于 api:xamarin 表单中的数据绑定

Data Binding in xamarin forms

我正在使用 xamarin.forms,并且我的项目中有两个输入字段。我需要使用 API 发布数据。我已经在 mvc 中创建了 API。 MVVM 在我的表单项目中使用,我有一个服务类和视图模型来发布数据,但我无法将数据传递给视图模型。
我的看法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
 public class testapi : ContentPage
{
    #region View Model
    public TestViewModel ViewModel { get; set; }
    #endregion

    bool isNewItem;
    Entry name;
    Entry age;

    #region Constructor
    public testapi()
    {
        #region Binding Context
        ViewModel = new TestViewModel();

        BindingContext = ViewModel.Testing;
        #endregion

        #region Using Triggers

        var emptyValTrig = new EventTrigger();
        emptyValTrig.Event ="TextChanged";
        emptyValTrig.Actions.Add(new EmptyTextValidation());
        #endregion
        name = new Entry
        {
            Keyboard = Keyboard.Text,
            TextColor = Color.Black,
            BackgroundColor = Color.Default,
            Placeholder ="Name",
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.FillAndExpand,
        };
        name.SetBinding(Label.TextProperty, ("Name"));
        name.Triggers.Add(emptyValTrig);
        age = new Entry
        {
            Keyboard = Keyboard.Text,
            TextColor = Color.Black,
            BackgroundColor = Color.Default,
            Placeholder ="Age",
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.FillAndExpand,

        };
        age.SetBinding(Label.TextProperty, ("Age"));
        age.Triggers.Add(emptyValTrig);

        Button loginButton = new Button
        {
            Text ="Login",
            BorderRadius = 5,
            TextColor = Color.White,
            BackgroundColor = Color.Gray,
            Command = ViewModel.SelectionChangedCommand
        };
        var dataTrigger = new DataTrigger(typeof(Button));
        dataTrigger.Binding = new Binding("Text.Length", BindingMode.Default, source: name);
        dataTrigger.Value = 0;
        dataTrigger.Setters.Add(new Setter { Property = Button.IsEnabledProperty, Value = false });
        loginButton.Triggers.Add(dataTrigger);

        var pageStack = new StackLayout();
        pageStack.Children.Add(name);
        pageStack.Children.Add(age);
        pageStack.Children.Add(loginButton);
        pageStack.Spacing = 10;
        Content = pageStack;

    }
    #endregion

}

和我的视图模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 public class TestViewModel : BaseViewModel
{
    //   Testing = new test();
    public TestViewModel()
    {
        Testing = new test();

        SelectionChangedCommand = new Command(async () =>
        {

            await RestaurantService.PostData<int, test>(RestaurantService.testdata, HttpMethod.Post, Testing).ContinueWith(test =>
            {

            }, TaskScheduler.FromCurrentSynchronizationContext());
        });

    }
    private test _test;
    public test Testing
    {
        get { return _test; }
        set
        {
            _test = value;
            OnPropertyChanged("Testing");
        }
    }

    public System.Windows.Input.ICommand SelectionChangedCommand { get; set; }
}

我也有一个服务类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 class RestaurantService
{
    public const string HostName ="http://192.168.0.44:100/api/";
    public const string item ="Order";
    public const string testdata ="Test";

    public static async Task< T > PostData<T, Tr>(string endpoint, HttpMethod method,
                                                  Tr content)
    {
        T returnResult = default(T);
        HttpClient client = null;
        try
        {
            client = new HttpClient();
            client.BaseAddress = new Uri(HostName);
            client.DefaultRequestHeaders.Add("Accept","application/json");
            client.Timeout = new TimeSpan(0, 0, 15);
            HttpResponseMessage result = null;
            StringContent data = null;
            if (content != null)
                data = new StringContent(JsonConvert.SerializeObject(content), UTF8Encoding.UTF8,"application/json");
            if (method == HttpMethod.Get)
                result = await client.GetAsync(endpoint);
            if (method == HttpMethod.Put)
                result = await client.PutAsync(endpoint, data);
            if (method == HttpMethod.Delete)
                result = await client.DeleteAsync(endpoint);
            if (method == HttpMethod.Post)
                result = await client.PostAsync(endpoint, data);
            if (result != null)
            {
                if (result.IsSuccessStatusCode
                                   && result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var json = result.Content.ReadAsStringAsync().Result;
                    returnResult = JsonConvert.DeserializeObject< T >(json);
                }
            }
        }
        catch (Exception ex)
        {

            Debug.WriteLine("Error fetching data:" + ex.Message);
        }
        finally
        {
            if (client != null)
                client.Dispose();
        }
        return returnResult;

    }
}

我无法将数据发送到我的视图模型以使用 api 发布。我应该怎么做


看来您在页面中绑定了错误的控件:

执行以下操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public class testapi : ContentPage
{
#region View Model
public TestViewModel ViewModel { get; set; }
#endregion

bool isNewItem;
Entry name;
Entry age;

#region Constructor
public testapi()
{
    #region Binding Context
    ViewModel = new TestViewModel();

    BindingContext = ViewModel.Testing;
    #endregion

    #region Using Triggers

    var emptyValTrig = new EventTrigger();
    emptyValTrig.Event ="TextChanged";
    emptyValTrig.Actions.Add(new EmptyTextValidation());
    #endregion
    name = new Entry
    {
        Keyboard = Keyboard.Text,
        TextColor = Color.Black,
        BackgroundColor = Color.Default,
        Placeholder ="Name",
        VerticalOptions = LayoutOptions.Center,
        HorizontalOptions = LayoutOptions.FillAndExpand,
    };
    name.SetBinding(Entry.TextProperty, ("Name"));
    name.Triggers.Add(emptyValTrig);
    age = new Entry
    {
        Keyboard = Keyboard.Text,
        TextColor = Color.Black,
        BackgroundColor = Color.Default,
        Placeholder ="Age",
        VerticalOptions = LayoutOptions.Center,
        HorizontalOptions = LayoutOptions.FillAndExpand,

    };
    age.SetBinding(Label.TextProperty, ("Age"));
    age.Triggers.Add(emptyValTrig);

    Button loginButton = new Button
    {
        Text ="Login",
        BorderRadius = 5,
        TextColor = Color.White,
        BackgroundColor = Color.Gray,
        Command = ViewModel.SelectionChangedCommand
    };
    var dataTrigger = new DataTrigger(typeof(Button));
    dataTrigger.Binding = new Binding("Text.Length", BindingMode.Default, source: name);
    dataTrigger.Value = 0;
    dataTrigger.Setters.Add(new Setter { Property = Button.IsEnabledProperty, Value = false });
    loginButton.Triggers.Add(dataTrigger);

    var pageStack = new StackLayout();
    pageStack.Children.Add(name);
    pageStack.Children.Add(age);
    pageStack.Children.Add(loginButton);
    pageStack.Spacing = 10;
    Content = pageStack;

}
#endregion

}

name.SetBinding(Entry.TextProperty, ("name"));

age.SetBinding(Entry.TextProperty, ("age"));

干杯!!