WPF案例展示

下拉框的数据绑定

枚举转换成对应的中文

设置数据上下文,设置数据源,设置数据格式转换器


        


        
        
            
        

下拉框的设置:

 

 注意ModelList必须为属性,写Get/set方法并且是Public类型,否则会找不到

 public ObservableCollection ModelList { get;  set ; } = new ObservableCollection();
        private SelfModel _selectedModel;
        public SelfModel SelectedModel
        {
            get => _selectedModel;
            set => SetProperty(ref _selectedModel, value);
        }

        public SelfViewModelAll()
        {
            // 填充枚举值
            foreach (SelfModel type in Enum.GetValues(typeof(SelfModel)))
            {
                ModelList.Add(type);
            }
        }

 枚举:

 public enum SelfModel : int
    {
        A= 0,
        B,
        C,
    }

 转换器:必须自己一个文档,否则写路径时找不到

 public class SelfModelC : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is SelfModel model)
            {
                switch (model)
                {
                    case SelfModel.A:
                        return "AA";
                    case SelfModel.C:
                        return "CC";
                    case SelfModel.B:
                        return "BB";
                    default:
                        return string.Empty;
                }
            }
            return string.Empty;
        }
        
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

你可能感兴趣的:(学习C#,wpf)