How to move my 2-way Data Binding from Code-Behind to XAML

女生的网名这么多〃 提交于 2019-12-02 04:05:36

Sorry I could not able to add comment, so posting it as answer. What I am suggesting you is just have separate class as your ViewModel e.g. NetWorkViewModel and inside your ViewModel create a property of your EXISTING OBJECT type and change the bindings in XAML as well.

public class NetworkViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private Network _model;
    public Network Model
    {
        get { return _model; }
        set
        {
            _model = value;
            OnPropertyChanged("Model");
        }
    }

    private void OnPropertyChanged(string propertyName) 
    {  }
}

public class Network : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int _id;
    public int Id
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }

    private void OnPropertyChanged(string propertyName)
    { }
}

In your Xaml

xmlns:vm="clr-namespace:net"
...
<Window.DataContext>
  <vm:NetworkViewModel />
</Window.DataContext>
...
<DockPanel Name="myTestPanel" >
    <TextBox Text="{Binding Path=Model.Id, Mode=TwoWay}"></TextBox>
</DockPanel>

This is one way of doing. Read some MVVM tutorial you will get some other ideas.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!