none
wpf mvvm模式下,如何绑定在ViewModel类中新建对象实例的属性? RRS feed

  • 问题

  • 想将ViewModel类中某些绑定的属性封装成一个类,然后在ViewModel创建该类的实例,然后将该实例的属性与相应的控件属性绑定。便于方面查看和管理绑定的后台属性。绑定代码怎么写?

    2016年12月12日 0:21

答案


  • Hi  轮回的齿轮,

    你可以参考下面代码实现的方式。

    XAML:

     <TextBox x:Name="textBox"  HorizontalAlignment="Left" Height="33" Margin="53,77,0,0" TextWrapping="Wrap" Text="{Binding Students.Name}" VerticalAlignment="Top" Width="169"/>

    XAML.CS:

                ViewModeltest vml = new ViewModeltest();
                textBox.DataContext = vml;
    
        public class ViewModeltest
        {
            Testviewclass _students;
            public Testviewclass Students
            { get { return _students; } set { _students = value; } }
    
            public ViewModeltest()
            {
                _students = new Testviewclass() { Name = "Test 1", Address = "00000" };
            }
        }
        public class Testviewclass
        {
            public string Name { get; set; }
            public string Address { get; set; }
        }
    

    Best Regards,

    Yohann Lu



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2016年12月12日 4:37
    版主