<DataGrid Name="grid_UserList" ItemsSource="{Binding ModelList}" AutoGenerateColumns="False" CanUserAddRows="False">
<DataGrid.Columns> <DataGridTextColumn Header="姓名" Binding="{Binding UserName}" Width="*" IsReadOnly="True" /> <DataGridTextColumn Header="ID" Binding="{Binding UserId}" Width="100" IsReadOnly="True" /> <DataGridTemplateColumn Header="職業(yè)" Width="*" > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <ComboBox x:Name="cb_Type" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.TypeList}" DisplayMemberPath="DisplayName" SelectedValue="{Binding UserType, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="EnumValue"/> <!--為了看出改變Combox時,,改變了當前選中實體的UserType屬性,,通過下面的TextBlock的Text的綁定來監(jiān)視--> <TextBlock Text="{Binding UserType}"></TextBlock> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> public class ViewModel
{ public ObservableCollection<Model> ModelList { get { return new ObservableCollection<Model>() { new Model(){UserName="甲",UserId="1",UserType=UserTypeEnum.Teacher}, new Model(){UserName="乙",UserId="2",UserType=UserTypeEnum.Student}, new Model(){UserName="甲",UserId="3",UserType=UserTypeEnum.Free_Agent}, new Model(){UserName="甲",UserId="4",UserType=UserTypeEnum.Staff}, }; } } public ObservableCollection<UserTypeInfo> TypeList
{ get { return new ObservableCollection<UserTypeInfo>() { new UserTypeInfo(){DisplayName="教師",EnumValue=UserTypeEnum.Teacher}, new UserTypeInfo(){DisplayName="學生",EnumValue=UserTypeEnum.Student}, new UserTypeInfo(){DisplayName="自由職業(yè)者",EnumValue=UserTypeEnum.Free_Agent}, new UserTypeInfo(){DisplayName="職員",EnumValue=UserTypeEnum.Staff}, }; }
} } /// <summary> /// 模擬實體類 /// </summary> public class Model { public string UserName { get; set; } public string UserId { get; set; } public UserTypeEnum UserType { get; set; } } /// <summary> /// 模擬實體類中某個屬性的枚舉值 /// </summary> public enum UserTypeEnum { Student, Teacher, Free_Agent, Staff } /// <summary> /// 模擬類別類 /// </summary> public class UserTypeInfo { public string DisplayName { get; set; } public UserTypeEnum EnumValue { get; set; } } |
|