2012-12-26 54 views
0

在我的項目中,我使用Silverlight5和MVVM模式。 我有以下:如何在Silverlight mvvm中將視圖的texbox值轉換爲viewmodel?

View  : Manager.xaml 
Code-Behind : Manager.Xaml.cs 
ViewModel : ManagerViewModel.cs 
我認爲

我有一個文本框,我已經分配的值是10。

Manager.xaml

<TextBox Name="gid" Visibility="Collapsed" /> 

Manager.xaml.cs

gid.Text=(((TextBlock)DG.Columns[5].GetCellContent(DG.SelectedItem)).Text); 
ManageViewModel vm = DataContext as ManageViewModel; 
      if (vm != null) 
      { 
       vm.EditCommand.Execute(); 
      } 

ManagerViewModel.cs:

private DelegateCommand _editCommand; 
    public DelegateCommand EditCommand 
    { 
     get 
     { 

      if (_editCommand == null) 
       _editCommand = new DelegateCommand(() => 
       { 
        **//Here i need to get the value that is assigned in the textbox.** 
        ANCViewModel.Show(); 
       }); 
      return _editCommand; 
     } 
    } 

這裏我的問題是我如何獲得在視圖文本框中分配的值ViewModel。任何幫助..?

+0

我認爲你應該使用雙向綁定 –

回答

0

據我所知,你的代碼。

ManageViewModel vm = DataContext as ManageViewModel; 

您的DataContext是ManageViewModel所以你應該使用這種背景下...

< TextBox Name="gid" Text={Binding MyTextPropertyInMyViewModel} 
    Visibility="Collapsed" why ? /> 

你的委託指令也是如此視圖模型,你可以在你的視圖模型很容易地使用MyTextPropertyInMyViewModel。

如果你使用MVVM,它意味着你使用了一個DataContext(或者它可以是一個資源)。你應該將它用於UI元素的源代碼和Commands。

通過這種方式您可以將業務和用戶界面分開。 ViewModel是我們的業務對象,您可能認爲Model是我們的實體。

所以你應該使用DataContext綁定DataGrid的,TextBlock和其他視覺元素,並在viewModel上管理你的商店。通過這種方式,您可以在其他地方使用您的視圖模型。即在您的移動應用程序。

相關問題