如何在WPF一个对象实例绑定? [英] How to bind a single object instance in WPF?

查看:143
本文介绍了如何在WPF一个对象实例绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个WPF新人,我一直在寻找了两天,没有运气。我有一个具有多个文本框控件WPF窗口,和一些属性的单个对象。该对象被传递到我的WPF窗口的codebehind在它的构造函数:

I am a WPF newcomer, and I've been searching for two days with no luck. I have a WPF window that has several text box controls, and a single object with some properties. This object is passed to the codebehind of my WPF window in it's constructor:

public partial class SettingsDialog : Window
{
    public SettingsObject AppSettings
    {
        get;
        set;
    }

    public SettingsDialog(SettingsObject settings)
    {
        this.AppSettings = settings;
        InitializeComponent();
    }
}

SettingsObject 看起来像这样(简化为清楚起见):

The SettingsObject looks something like this (simplified for clarity):

public class SettingsObject
{
    public string Setting1 { get; set; }
    public string Setting2 { get; set; }
    public string Setting3 { get; set; }

    public SettingsObject()
    {
        this.Setting1 = "ABC";
        this.Setting2 = "DEF";
        this.Setting3 = "GHI";
    }
}

和我的WPF窗口(简体):

And my WPF window (simplified):

<Window x:Class="MyProgram.SettingsDialog" 
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            DataContext="{Binding Source=AppSettings}">
    <Grid>
        <TextBox Name="Setting1Textbox" Text="{Binding Path=Setting1}"></TextBox>
        <TextBox Name="Setting2Textbox" Text="{Binding Path=Setting2}"></TextBox>
        <TextBox Name="Setting3Textbox" Text="{Binding Path=Setting3}"></TextBox>
    </Grid>
</Window>

你怎么acheive在这种情况下双向绑定?我试过你所看到的上面(和这么多),但没有什么工作!

How do you acheive two-way binding in this situation? I've tried what you see above (and so much more) but nothing works!

推荐答案

你有窗口的DataContext属性设置为您的AppSettings的实例?

Have you set the DataContext property of the window to your instance of AppSettings?

public SettingsDialog(SettingsObject settings)
{

    InitializeComponent();

    //While this line should work above InitializeComponent,
    // it's a good idea to put your code afterwards.
    this.AppSettings = settings;

    //This hooks up the windows data source to your object.
    this.DataContext = settings;
}

这篇关于如何在WPF一个对象实例绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆