我一直在使用MVVM Light處理示例項目,我想知道如何綁定TextBox Text值並將其傳遞給視圖到視圖模型。這是我第一次使用MVVM Light,所以我是新手。如何將TextBox中的值綁定到Mvvm Light中的視圖模型
基本上,用戶將輸入項目名稱到文本框名稱中,然後單擊新建項目按鈕,該按鈕應該生成一個以輸入到項目名稱文本框中的內容命名的數據庫。
查看:
<UserControl x:Class="Sample.Views.NavigationTree.NewProjectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mui="http://firstfloorsoftware.com/ModernUI"
xmlns:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
DataContext="{Binding NewProjectView, Source={StaticResource Locator}}">
<Grid>
<StackPanel Orientation="Vertical" HorizontalAlignment="Left">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<mui:BBCodeBlock BBCode="Project Name"/>
<Label Width="10"/>
<TextBox Text="{Binding ProjName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Width="120"/>
</StackPanel>
<Label Height="10"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Label Width="85"/>
<Button Content="New Project" Margin="0,0,3,0" Command="{Binding AddProjectCommand}" IsEnabled="{Binding IsUserAdmin}" Grid.Column="2" Grid.Row="0"/>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
視圖模型:
using Sample.Model.Database;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Text;
namespace Sample.ViewModel
{
/// <summary>
/// This class contains properties that a View can data bind to.
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class NewProjectViewModel : ViewModelBase
{
private string _projName;
//Binding AddProjectCommand
public RelayCommand AddProjectCommand { get; set; }
private string consoleText { get; set; }
private StringBuilder consoleBuilder = new StringBuilder(360);
/// <summary>
/// Initializes a new instance of the NewProjectViewModel class.
/// </summary>
public NewProjectViewModel()
{
this.AddProjectCommand = new RelayCommand(() => AddProject());
}
public void AddProject()
{
ProjectDbInteraction.CreateProjectDb(_projName);
}
public string ProjName
{
get { return _projName; }
set
{
if (value != _projName)
{
_projName = value;
RaisePropertyChanged("ProjName");
}
}
}
public string ConsoleText
{
get { return consoleText; }
set
{
consoleBuilder.Append(value);
consoleText = consoleBuilder.ToString();
RaisePropertyChanged("ConsoleText");
}
}
}
}
那麼,如何通過ProjName結合並從視圖向視圖模型?
我添加了整個視圖和視圖模型。 – yams 2014-11-06 16:15:18
您是否嘗試通過讓用戶鍵入文本框來設置ProjName屬性?如果是這樣,你不能使用綁定在那裏的單向路徑。刪除它或將其設置爲TwoWay或OneWayToSource,如果這是你想要的。 OneWay將只爲來自您的視圖模型的值 – 2014-11-06 16:39:19
哦,該死的你是對的。 DId甚至沒有想到這一點。 – yams 2014-11-06 16:57:51