如何在WPF中绑定单个对象实例?

时间:2011-02-26 19:08:48

标签: c# wpf xaml binding

我是WPF的新人,我一直在寻找两天没有运气。我有一个WPF窗口,它有几个文本框控件,以及一个具有一些属性的对象。这个对象在它的构造函数中传递给我的WPF窗口的代码隐藏:

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

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

SettingsObject看起来像这样(为简洁起见而简化):

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窗口(简化):

<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>

在这种情况下,你如何实现双向绑定?我已经尝试了你上面看到的(以及更多),但没有任何作用!

1 个答案:

答案 0 :(得分:3)

您是否已将窗口的DataContext属性设置为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;
}