ObjectDataProvider

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

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

App.xml


<!-- 引入System命名空间 clr-namespace:System;assembly=mscorlib-->
<Application x:Class="WpfTest1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfTest1"
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             StartupUri="MainWindow.xaml">
   
    <Application.Resources>
        <ObjectDataProvider x:Key="odp" ObjectType="{x:Type local:ObjectDataSource}" MethodName="Add">
            <ObjectDataProvider.ConstructorParameters>
                <sys:Int32>7</sys:Int32>
                <sys:Int32>8</sys:Int32>
            </ObjectDataProvider.ConstructorParameters>
            <ObjectDataProvider.MethodParameters>
                <sys:String>x+y=</sys:String>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Application.Resources>
</Application>


ObjectDataSource.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfTest1
{
    public class ObjectDataSource
    {
        private int x;
        private int y;
        

        public ObjectDataSource(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public string Add(string prefix)
        {
            return prefix + (x + y);
        }
    }
}


MainWindow.xaml

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

效果

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号