我一直在使用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