zoukankan      html  css  js  c++  java
  • wpf 对象绑定到Xaml

    在开发中经常需要将后台数据对象直接绑定到前台XAML,可以通过在<Window.Resources>添加对象的定义,然后再XAML中就可以使用该对象了。比如需要在前台使用自定义的Person类。

      public class Person
        {
            private string _name = "张三";
    
            public Person() { }
    
            public string Name1
            {
                get
                {
                    return _name;
                }
                set
                {
                    this._name = value;
                }
            }
        }

    在前台引用

    <Window x:Class="WpfApplication2.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:WpfApplication2"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <local:Person  x:Key="MyPerson"  />
        </Window.Resources>
        <Grid>
            <TextBox Width="100" Height="25">
                <TextBox.Text>
                    <Binding Source="{StaticResource MyPerson}" Path="Name1"/>
                </TextBox.Text>
            </TextBox>
        </Grid>
    </Window>

    即可完成对应关系的绑定


    或者使用在前台使用ObjectDataProvider完成绑定
    <Window x:Class="WpfApplication2.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:WpfApplication2"
            mc:Ignorable="d"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <ObjectDataProvider x:Key="odp" ObjectType="{x:Type local:Person}" />
        </Window.Resources>
        <Grid>
            <TextBox Width="100" Height="25">
                <TextBox.Text>
                    <Binding Source="{StaticResource odp}" Path="Name1"/>
                </TextBox.Text>
            </TextBox>

        </Grid>
    </Window>

    也可以完成对应关系的绑定

  • 相关阅读:
    跟着Android学设计模式:代理(proxy)
    阿里巴巴无敌公关能力鲜为人知的内幕
    Linux与JVM的内存关系分析
    树莓派学习笔记——交叉编译练习之SQLite3安装
    atitit.eclipse 新特性总结3.1--4.3
    JAVA-1-学习历程1:基础知识1
    [OpenNebula]中间件訪问驱动程序
    RESTFul中的那些事(1)---在RESTFul中,HTTP Put和Patch操作的差别?
    再看数据库——(3)触发器
    QT5: QApplication, no such file or directory
  • 原文地址:https://www.cnblogs.com/KQNLL/p/7111601.html
Copyright © 2011-2022 走看看