【问题标题】:How to set ViewModel's property from View without explicit type conversion如何在没有显式类型转换的情况下从 View 设置 ViewModel 属性
【发布时间】:2013-02-19 08:00:28
【问题描述】:

我是 mvvm 的新手,所以我真的需要你的帮助。

在我的 wp7 应用程序中,我正在尝试使用 MVVM Light 工具包。 我有两个视图:“主要”和 2 模式“新”,用于添加一些项目和编辑一些项目。

class Item
{
  public int ID {get; set;}
  public string Name {get; set;}
}

当我从 MainView 导航到 NewView 时,如果我想编辑项目,我会在查询字符串中添加“Name”参数。 在 NewView 我有文本框:

<TextBox Grid.Column="1" Name="txtListName" Text="{Binding ItemName}"/>

新视图模型:

class NewViewModel
{
  public string ItemName { get; set; }
}

我怎样才能像这样在 NewView.xaml.cs 中从 NewView 没有代码设置 ItemName 属性

(this.DataContext as NewViewModel).ItemName = name;

提前致谢!

【问题讨论】:

  • 如果 ViewModel 有值,只需要添加 View 和 ViewModel 之间的双向绑定以及 DataContext 的设置即可。
  • 我正在使用 ViewModelLocator 创建 NewViewModel
    DataContext="{Binding New, Source={StaticResource Locator}}"。我正在解析 NewView 上的查询字符串,那么如何在没有显式类型转换的情况下从 NewView 初始化 NewViewModel 字段?我尝试使用查询字符串中的值从 NewView Text 属性设置文本框(使用两种方式绑定),但尚未设置我的 NewViewModel 属性。

标签: c# xaml mvvm windows-phone-7.1 mvvm-light


【解决方案1】:

我已经决定了这个问题。在 NewView 上,我设置为文本框双向绑定:

<TextBox Grid.Column="1" Name="txtListName" Text="{Binding ItemName,Mode=TwoWay}"/>

然后在视图的加载事件中,我设置了这个文本框的文本属性:

void NewView_Loaded(object sender, RoutedEventArgs e)
{
    String name;
    if (NavigationContext.QueryString.TryGetValue("Name", out name))
        this.txtListName.Text = name;
}

在设置 NewViewModel 的属性 ItemName 之后!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2013-11-24
    • 2014-04-05
    • 1970-01-01
    相关资源
    最近更新 更多