ObjectDataProvider

作者:追风剑情 发布于:2020-5-6 13:48 分类:C#

通过ObjectDataProvider可以实现数据源与方法绑定

App.xml


  1. <!-- 引入System命名空间 clr-namespace:System;assembly=mscorlib-->
  2. <Application x:Class="WpfTest1.App"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="clr-namespace:WpfTest1"
  6. xmlns:sys="clr-namespace:System;assembly=mscorlib"
  7. StartupUri="MainWindow.xaml">
  8. <Application.Resources>
  9. <ObjectDataProvider x:Key="odp" ObjectType="{x:Type local:ObjectDataSource}" MethodName="Add">
  10. <ObjectDataProvider.ConstructorParameters>
  11. <sys:Int32>7</sys:Int32>
  12. <sys:Int32>8</sys:Int32>
  13. </ObjectDataProvider.ConstructorParameters>
  14. <ObjectDataProvider.MethodParameters>
  15. <sys:String>x+y=</sys:String>
  16. </ObjectDataProvider.MethodParameters>
  17. </ObjectDataProvider>
  18. </Application.Resources>
  19. </Application>


ObjectDataSource.cs


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace WpfTest1
  8. {
  9. public class ObjectDataSource
  10. {
  11. private int x;
  12. private int y;
  13.  
  14. public ObjectDataSource(int x, int y)
  15. {
  16. this.x = x;
  17. this.y = y;
  18. }
  19.  
  20. public string Add(string prefix)
  21. {
  22. return prefix + (x + y);
  23. }
  24. }
  25. }


MainWindow.xaml

  1. <Window x:Class="WpfTest1.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:local="clr-namespace:WpfTest1"
  7. mc:Ignorable="d"
  8. Title="MainWindow" Height="450" Width="800">
  9. <Grid>
  10. <TextBlock Text="{Binding Source={StaticResource odp}}"/>
  11. </Grid>
  12. </Window>

效果

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号