MarkupExtension 标记扩展

个人觉得这个作用IValueConverter没有啥区别。。。。

看用法

准备一个类

 1 public class ListMarkupExtension : MarkupExtension
 2     {
 3         private List<string> _items1 = new List<string>() { "A", "B", "C" };
 4 
 5         private List<int> _items2 = new List<int>() { 3, 2, 1 };
 6 
 7         private string _type;
 8 
 9         /// <summary>
10         /// 标记扩展允许软件开发人员在XAML中使用带有(一个)参数的非默认构造函数
11         /// </summary>
12         /// <param name="type"></param>
13         public ListMarkupExtension(string type)
14         {
15             _type = type;
16         }
17 
18         public override object ProvideValue(IServiceProvider serviceProvider)
19         {
20             switch (_type)
21             {
22                 case "text":
23                     return _items1;
24 
25                 case "num":
26                     return _items2;
27 
28                 default:
29                     return null;
30             }
31         }
32     }

xaml 绑定

 1 <Window
 2     x:Class="MarkupExtension使用方法.MainWindow"
 3     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 4     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 5     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 6     xmlns:local="clr-namespace:MarkupExtension使用方法"
 7     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 8     Title="MainWindow"
 9     Width="800"
10     Height="450"
11     FontSize="30"
12     mc:Ignorable="d">
13     <Grid>
14         <StackPanel
15             Width="300"
16             HorizontalAlignment="Center"
17             Orientation="Vertical">
18             <ListView ItemsSource="{local:ListMarkup num}" />
19         </StackPanel>
20     </Grid>
21 </Window>

运行效果

 

 

posted @ 2021-10-22 17:06  只吃肉不喝酒  阅读(154)  评论(0编辑  收藏  举报