欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF--绑定自定义数据类型

程序员文章站 2022-03-04 11:27:44
...

WPF作为数据绑定的目标:
使用DataContext属性,表示当前控件中的每个元素都绑定此数据:
数据类型定义:

public class FamilyData
{
    private string m_familyName;
    private string m_width;
    private string m_height;

    public string FamilyName
    {
        get { return m_familyName; }
        set { m_familyName = value; }
    }

    public string Width
    {
        get { return m_width; }
        set{ m_width = value; }
    }

    public string Height
    {
        get { return m_height; }
        set { m_height = value; }
    }
}

XAML:

<Grid>
    <StackPanel Name="stackPanel" Orientation="Vertical" HorizontalAlignment="Left">
        <TextBlock Name="txtName" Text="{Binding FamilyName}"/>
       <TextBlock Name="txtWidth" Text="{Binding Width}"/>
        <TextBlock Name="txtHeight" Text="{Binding Height}"/>
       <Button Name="Bnt" Click="btn_Click" Content="确定" MaxWidth="30"/>
    </StackPanel>
</Grid>

对应xaml.cs代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Init();
    }

    private FamilyData familyData;
    public void Init()
    {
        familyData = new FamilyData();
        familyData.FamilyName = "支吊架族";
        familyData.Width = "200";
        familyData.Height = "500";
        stackPanel.DataContext = familyData;
    }

    private void btn_Click(object sender, RoutedEventArgs e)
    {
        familyData = new FamilyData();
        familyData.FamilyName = "管道附件族";
        familyData.Width = "200W";
        familyData.Height = "500H";
        stackPanel.DataContext = familyData;
    }
}
相关标签: WPF数据绑定