WPF案例展示

下拉框的数据绑定

枚举转换成对应的中文

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

复制代码
<UserControl.DataContext>
        <ViewModels:SelfViewModelAll />
</UserControl.DataContext>
<UserControl.Resources>
        <Model:SelfModelC x:Key="SelfModelC" d:IsDataSource="True"/>
        <DataTemplate x:Key="EnumItemTemplate">
            <TextBlock Text="{Binding Converter={StaticResource SelfModelC}}" />
        </DataTemplate>
</UserControl.Resources>

下拉框的设置:

复制代码
 <ComboBox Name="ModelChoose" 
          ItemsSource="{Binding ModelList //数据来源(链表),diagnostics:PresentationTraceSources.TraceLevel=High}" //测试
          SelectedItem="{Binding SelectedModel, Mode=TwoWay}" //选择的项
          ItemTemplate="{StaticResource EnumItemTemplate}" //转换器
          HorizontalAlignment="Stretch" 
          VerticalAlignment="Stretch" Grid.Row="3" Grid.Column="1" 
          Height="25" />

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

复制代码
 public ObservableCollection<SelfModel> ModelList { get;  set ; } = new ObservableCollection<SelfModel>();
        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();
        }
    }
相关推荐
玖笙&2 天前
✨WPF编程基础【2.1】布局原则
c++·wpf·visual studio
玖笙&2 天前
✨WPF编程基础【2.2】:布局面板实战
c++·wpf·visual studio
SEO-狼术2 天前
.NET WPF 数据编辑器集合提供列表框控件
.net·wpf
FuckPatience7 天前
WPF 具有跨线程功能的UI元素
wpf
诗仙&李白7 天前
HEFrame.WpfUI :一个现代化的 开源 WPF UI库
ui·开源·wpf
He BianGu7 天前
【笔记】在WPF中Binding里的详细功能介绍
笔记·wpf
He BianGu7 天前
【笔记】在WPF中 BulletDecorator 的功能、使用方式并对比 HeaderedContentControl 与常见 Panel 布局的区别
笔记·wpf
123梦野8 天前
WPF——效果和可视化对象
wpf
He BianGu8 天前
【笔记】在WPF中Decorator是什么以及何时优先考虑 Decorator 派生类
笔记·wpf
时光追逐者8 天前
一款专门为 WPF 打造的开源 Office 风格用户界面控件库
ui·开源·c#·.net·wpf