【问题标题】:How to bind a textbox.Text property in WPF MMVM design如何在 WPF MVVM 设计中绑定 textbox.Text 属性
【发布时间】:2012-11-02 10:11:52
【问题描述】:

所以我正在尝试学习 WPF 中的 MVVM 设计模式,我想做以下事情:

在外部类中,我有一个 ObservableCollection _students,它使用 MVVM 设计模式绑定到 WPF 窗口上的列表视图。列表视图仅显示学生的姓名和年龄。

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Course { get; set; }
    public DateTime JoiningDate { get; set; }
}


public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Student> _students;

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

    public ObservableCollection<Student> Students
    {
        get
        {
            return _students;
        }
        set
        {
            _students = value;
            NotifyPropertyChanged("Students");
        }
    }

一切都好,但我想放置一个 TextBox 并将其设置为显示列表视图的选定项目的课程属性。这意味着我必须

  1. 获取列表视图的选中索引(ok)
  2. 将 textbox.Text 属性绑定到 Students[那个索引].Course

我被困在 2 点。有什么帮助吗?

【问题讨论】:

  • 不确定语法,但您可以将 TextBox 绑定到 ListBox &lt;TextBox Text="{Binding ElementName=StudentsList, Path=SelectedValue.Course}"/&gt;SelectedValue - 尽管我认为这不会起作用。

标签: wpf mvvm


【解决方案1】:

我会用另一种方式解决这个问题。

看看这个post .

另一种方法是您的 ViewModel 包含绑定到 listView 的 SelectedItem 的学生属性(例如 SelectedStudent)。然后你可以处理这个

{Binding Path=SelectedStudent.Course}

【讨论】:

    【解决方案2】:

    假设您将列表视图绑定到 SampleData 类型的集合,如下所示:

    SampleData.cs

    public class SampleData
    {
        public int Id { get; set; }
    
        public string Text { get; set; }
    
        public decimal Value { get; set; }
    }
    

    然后将 ListView ItemsSource 绑定到一个集合。将 ItemsSource 属性绑定到 ViewModel 上的属性或在代码隐藏中绑定它都没有关系,如下面的代码。

    var source = new List<SampleData>();
    
    source.Add(new SampleData() { Id = 1, Text = "AAA" });
    source.Add(new SampleData() { Id = 2, Text = "BBB" });
    source.Add(new SampleData() { Id = 3, Text = "CCC" });
    source.Add(new SampleData() { Id = 4, Text = "DDD" });
    source.Add(new SampleData() { Id = 5, Text = "EEE" });
    

    您可以直接在 View 上将 TextBox 的 Text 属性绑定到 SelectedItem。

    <StackPanel Orientation="Horizontal">
        <ListView x:Name="listView1" />
    
        <TextBox Text="{Binding ElementName=listView1, Path=SelectedItem.Text}" />
    </StackPanel>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2012-07-20
      相关资源
      最近更新 更多