【问题标题】:Data Binding in xamarin formsxamarin 表单中的数据绑定
【发布时间】:2016-06-26 06:09:21
【问题描述】:

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

 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

}

和我的视图模型

 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; }
}

我也有一个服务类

 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 发布。我该怎么办

【问题讨论】:

    标签: api mvvm xamarin xamarin.forms


    【解决方案1】:

    您似乎在页面中绑定了错误的控件:

    执行以下操作:

    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"));

    干杯!!

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 2020-08-27
      • 2019-05-24
      • 2018-02-16
      • 2021-04-18
      相关资源
      最近更新 更多