Mvvm将文本框值从View传递给ViewModel

时间:2016-11-14 13:25:36

标签: c# mvvm uwp

MVVM模式目前让我疯狂,似乎比它需要的复杂得多。

如果想要将一个对象从我的View传递给我的ViewModel,是否有一种简单的方法可以执行此操作,或者我是否需要为每个变量创建一个getter / setter并手动将它们添加到对象中。

我也看到人们像这样使用PropertyInfo,但我似乎无法从对象中获取变量

Xaml代码(缩写):

Did you create indexes on all join fields between tables? 
To accelerate processing without changing the structure of your current query, you must create these indexes.
Note that for fields calculated as _convert (datetime, CONVERT (varchar (8), tablo.T, 112))_, you must create function based index and here is a useful link that can help you: 
[http://stackoverflow.com/questions/22168213/function-based-indexes-in-sql-server][1].
Normally with this, executing your query will not result in a timeout.

hope this can help.

视图模型:

        <TextBlock x:Name="txbName" Text="Name: " FontSize="15"  Margin="0, 0, 10, 0"/>
        <TextBox x:Name="txtName" Text="{Binding ProductToAdd.ProductName, Mode=TwoWay}"/>

        <TextBlock x:Name="txbWarehouse" Text="Warehouse: " FontSize="15" Margin="0, 10, 10, 0"/>
        <TextBox x:Name="txtWarehouse"Width="95" Margin="0, 10, 0, 0" Text="{Binding ProductToAdd.WarehouseID, Mode=TwoWay}"/>

        <Button x:Name="btnAdd" Content="Add product" Margin="0, 20, 0, 0" Command="{Binding AddCommand}"></Button>

模型中的产品代码:

    public ICommand AddCommand { get; set; }

    public AddProductPageViewModel(INavigationService navigationService)
    {
        AddCommand = new CustomCommand(OnAddProduct, CanRedirect);
        this.navigationService = navigationService;
    }

    private void RaisePropertyChanged(string propertyName){
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public Product ProductToAdd
    {
        get
        {
            return productToAdd;
        }
        set
        {
            productToAdd = value;
            RaisePropertyChanged("ProductToAdd");
        }
    }

    private void OnAddProduct(object obj)
    {
        // Get all product vars 
        //Debug.Write(productToAdd.ProductName);
    }

1 个答案:

答案 0 :(得分:1)

您的ViewModel通常绑定到您的View。然后,您的AddCommand将使用这些值来执行您希望它执行的操作。因此,您的ViewModel应该具有ProductToAdd属性。

您也可以通过ProductToAddCommandParameter对象传递给命令,但仍需要在某处定义,并且从您的示例中看似没有必要。< / p>