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

后端 未结 1 610
攒了一身酷
攒了一身酷 2021-01-26 19:53

Relatively new to WFP and C# (longtime PHP programmer)...

I successfully set up 2-WAY data binding between a TextBox and a Property of an Object. I was able to establis

相关标签:
1条回答
  • 2021-01-26 20:18

    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.

    0 讨论(0)
提交回复
热议问题