Looping over XAML defined labels

后端 未结 6 1296
傲寒
傲寒 2021-01-18 08:58

I have a WPF application with many labels.

         


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-01-18 09:21

    You can make it with binding !

    xaml view:

    
        
            
                
        
    
    

    in code behind in the constructor:

    DataContext = new ViewModelClass();
    

    in ViewModelClass:

    class ViewModelClass : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void NotifyPropertyChanged(string name)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
    
            private ObservableCollection _List = new ObservableCollection();
            public ObservableCollection List
            {
                get { return _List; }
                set
                {
                    _List = value;
                    NotifyPropertyChanged("List");
                }
            }
    
            public ViewModelClass()
            {
                List = new ObservableCollection
                    {
                        new StringObject {Value = "your"},
                        new StringObject {Value = "list"},
                        new StringObject {Value = "of"},
                        new StringObject {Value = "string"}
                    };
            }
        }
    
        public class StringObject
        {
            public string Value { get; set; }
        }
    

    Be careful with a collection with type string it doesn't work, you have to use an object => StringObject

提交回复
热议问题