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();
        }
    }
相关推荐
dotent·14 小时前
C#基于WPF UI框架的通用基础上位机测试WPF框架
ui·c#·wpf
咩图2 天前
WPF+Prism8.0.0.1909+C#创建一个桌面程序
c#·wpf·prism
雁于飞2 天前
分布式基础
java·spring boot·分布式·spring·wpf·cloud native
oioihoii2 天前
WPF入门指南:解析默认项目结构
wpf
极客智造2 天前
深入解析 ReactiveUI:WPF 响应式 MVVM 开发的 “终极方案”
wpf
Macbethad4 天前
使用WPF编写一个多维度伺服系统的程序
大数据·hadoop·wpf
lingxiao168884 天前
WPF Prism框架应用
c#·wpf·prism
Macbethad4 天前
使用WPF编写一个Ethercat主站的程序
wpf
难搞靓仔4 天前
WPF 弹出窗体Popup
wpf·popup
Macbethad4 天前
使用WPF编写一个MODBUSTCP通信的程序
wpf