gpt4 book ai didi

c# - 如何在 WPF 中绑定(bind)单个对象实例?

转载 作者:行者123 更新时间:2023-11-30 22:40:35 24 4
gpt4 key购买 nike

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

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

最佳答案

您是否已将窗口的 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;
}

关于c# - 如何在 WPF 中绑定(bind)单个对象实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com