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>

也可以完成對應關系的綁定


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM