【问题标题】:TwoWay Binding on Windows Phone 8.1 app, using MVVMWindows Phone 8.1 应用程序上的双向绑定,使用 MVVM
【发布时间】:2016-04-04 04:35:43
【问题描述】:

我正在使用 MVVM 开发销售管理系统,但在保存视图中输入的数据时遇到问题。我假设 TwoWay Binding 意味着在视图上输入的所有值都应该传递给 ViewModel,反之亦然,对吗?

查看

 <TextBox x:Name="NameText"
             Grid.ColumnSpan="2"
             Grid.Row="2"
             Header="Nombre:"
             Style="{StaticResource RegisterTextBoxStyle}"
             Text="{Binding Product.Name, Mode=TwoWay}"/>
    <ComboBox x:Name="UnitCombo"
              Grid.Row="3"
              Grid.ColumnSpan="2"
              Header="Unidad:"
              PlaceholderText="Elige la medida"
              Style="{StaticResource RegisterComboBoxStyle}"
              ItemsSource="{Binding Path=UnitsSource, Mode=OneWay}"
              SelectedValue="{Binding SelectedUnit, Mode=TwoWay}"/>
    <TextBox x:Name="CostText"
             Grid.Column="0"
             Grid.Row="4"
             Header="Costo:"
             Style="{StaticResource RegisterTextBoxStyle}"
             Text="{Binding Product.Cost, Mode=TwoWay}"/>
    <TextBox x:Name="PriceText"
             Grid.Column="1"
             Grid.Row="4"
             Header="Precio:"
             Style="{StaticResource RegisterTextBoxStyle}"
             Text="{Binding Product.Price, Mode=TwoWay}"/>
    <ToggleSwitch x:Name="ActiveToggle"
                  Grid.Column="1"
                  Grid.Row="5"
                  Style="{StaticResource RegisterToggleSwithStyle}"
                  IsOn="{Binding Product.Active, Mode=TwoWay}"/>

View 使用 SaveProduct 命令保存在视图中输入的所有值,它的调用来自:

        <AppBarButton Icon="Accept" Label="Añadir" Command="{Binding Path=SaveCommand}"/>

我在代码隐藏上建立了 DataContext

public AddProduct()
    {
        InitializeComponent();
        DataContext = new ProductListViewModel();
    }

ProductListViewModel

namespace BillingShop.ViewModel
{
    public class ProductListViewModel : ViewModelBase, INavigable
    {
        public ObservableCollection<ProductViewModel> Items { get; private set; }
    private DelegateCommand _saveProduct;
    public bool IsUpdating { get; set; }
    public ProductViewModel Product { get; set; }
    public Visibility UpdatingVisibility => (IsUpdating || Items == null || Items.Count == 0) ? Visibility.Visible : Visibility.Collapsed;

    public ProductListViewModel()
    {
        if (IsInDesignMode)
        {
            return;
        }
        _saveProduct = new DelegateCommand(SaveCommand_Executed);
    }

    #region Product Members

    private string _unit;
    public string SelectedUnit
    {
        get { return _unit; }
        set
        {
            _unit = value;
            OnPropertyChanged();
        }
    }

    #endregion


    public IEnumerable<RegisteredUnits> UnitsSource => Enum.GetValues(typeof(RegisteredUnits)).Cast<RegisteredUnits>();

    public ICommand SaveCommand => _saveProduct;

    private void SaveCommand_Executed()
    {
        var product = new Product
        {
            Name = Product.Name,
            Unit = Product.Unit,
            Cost = Convert.ToDouble(Product.Cost),
            Price = Convert.ToDouble(Product.Price),
            Active = Convert.ToBoolean(Product.Active)
        };
        ProductManager.SaveProduct(product);
    }

    public void PopulateProductViewModel(ProductViewModel entry)
    {
        Product = entry;
        OnPropertyChanged("Product");
    }
    public Product GetProduct()
    {
        return Product?.GetProduct();
    }
}

}

ProductViewModel

public class ProductViewModel : ViewModelBase
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Unit { get; set; }
    public double Cost { get; set; }
    public double Price { get; set; }
    public bool Active { get; set; }
    public List<SalesDetails> SalesDetail { get; set; }

    public ProductViewModel()
    {
    }

    public ProductViewModel(Product item)
    {
        Update(item);
    }
    public void Update (Product item)
    {
        Id = item.ID;
        Name = item.Name;
        Unit = item.Unit;
        Cost = item.Cost;
        Price = item.Price;
        Active = item.Active;
        SalesDetail = item.SalesDetail;
    }

    public Product GetProduct()
    {
        return new Product
        {
            ID = Id,
            Name = Name,
            Unit = Unit,
            Cost = Cost,
            Price = Price,
            Active = Active,
            SalesDetail = SalesDetail
        };
    }
}

SaveProduct 执行时,Product 类显示为空,我的视图值呢?我的代码有什么问题?

感谢所有帮助我的人,我将我的存储库链接放在这里,也许有人想深入了解我的代码: https://github.com/adoibarra/BillingShop

编辑:这是我的产品类

public class Product : IBusinessEntity
{
    /// <summary>
    /// Represents a Product.
    /// </summary>
    public Product()
    {
    }


    /// <summary>
    /// Get or sets the product identifier.
    /// </summary>
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    /// <summary>
    /// Get or sets the product name.
    /// </summary>
    [MaxLength(40)]
    public string Name { get; set; }
    /// <summary>
    /// Get or sets if the product can be measured in units or kilograms.
    /// </summary>
    public string Unit { get; set; }
    /// <summary>
    /// Get or sets the product cost.
    /// </summary>
    public double Cost { get; set; }
    /// <summary>
    /// Get or sets the product price.
    /// </summary>
    public double Price { get; set; }
    /// <summary>
    /// Get or sets the product state.
    /// </summary>
    public bool Active { get; set; }
    /// <summary>
    /// One-To-Many relationship with SalesDetails.
    /// </summary>
    [OneToMany(CascadeOperations = CascadeOperation.All)]
    public List<SalesDetails> SalesDetail { get; set; }


}

【问题讨论】:

  • 您在哪里创建 Product 类对象?除非您实例化,否则它将为空。这里的两种方式绑定是它将填充视图和视图模型中的名称、成本等属性。但我猜你的 Product 对象本身是空的,它将如何填充它的属性?
  • 感谢@Archana,我编辑了我的问题以添加该类,它在 BusinessLayer 命名空间中,我在获得产品时没有任何问题,但是当我尝试设置值时却令人沮丧。有什么想法吗?
  • 不,我问过你在哪里以及如何在 ProductListViewModel 中创建 Product 对象?
  • @Arcana 你是说这一行吗: public ProductViewModel Product { get;放; } ?
  • 是的。那是声明对吗?

标签: c# xaml mvvm binding windows-phone-8.1


【解决方案1】:

解决方案是在 ProductListViewModel 构造函数中初始化 Product 属性:

public class ProductListViewModel
{
   public ProductListViewModel ()
   {
      Product = new ProductViewModel();
   }
   .
   .
   .
}

感谢 Weimar Yamit Moreno Perez 的帮助,以及 Archana 的干预。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多