gpt4 book ai didi

c# - 如何将 Silverlight UI 绑定(bind)到 .NET 类

转载 作者:太空宇宙 更新时间:2023-11-03 11:46:39 25 4
gpt4 key购买 nike

我正在考虑将某个 silverlight UI 绑定(bind)到 C# 类。在下面的示例代码中,XAML 页面中有两个文本框。对一个文本框所做的任何更改都会在另一个文本框失去焦点时反射(reflect)在另一个文本框上,反之亦然。虽然我的示例按我希望的方式工作,但我不知道引擎盖下发生了什么以及它是如何工作的。

这是C#代码

public class Person : INotifyPropertyChanged
{
public string FirstName
{
get
{return firstname;}

set
{ firstname = value;
FirePropertyChanged("FirstName");
}

}
private string firstname;

void FirePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}

public event PropertyChangedEventHandler PropertyChanged;
}

mainpage.xaml中的Grid

<Grid x:Name="MyLayoutRoot" Background="White" ShowGridLines="True"> 
<TextBox Text="{Binding FirstName, Mode=TwoWay}" Grid.Column="1"></TextBox>
<TextBox Text="{Binding FirstName, Mode=TwoWay}" Grid.Column="1" Grid.Row="3"></TextBox>
</Grid>

Mainpage.xaml 的代码隐藏

    public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Page_Loaded);
}

void Page_Loaded(object sender, RoutedEventArgs e)
{
Person p = new Person()
{
FirstName ="Dee"
};
MyLayoutRoot.DataContext = p;
}
}

到目前为止我的理解是这样的,现在有点模糊:

xaml(mainpage.xaml) 中的文本框根据它的“绑定(bind)”标签知道要绑定(bind)到什么属性,从它在 xaml 代码隐藏文件 (mainpage.xaml.cs) 中设置的类 (Person)通过在那里使用 datacontext 属性。

INotifyPropertyChanged 是 person 类中的一个接口(interface),它提供了一些 Hook ,允许 Xaml UI 知道 Firstname 属性何时在 UI 中更改。在设置 Firstname 属性的那一刻,将调用 FirePropertyChanged 方法来触发此事件 PropertyChangedEventHandler,如该行中所实现的那样

PropertyChanged(this, new PropertyChangedEventArgs(property));

当其中一个文本框发生变化并失去焦点时,任何人都可以详细说明此时此刻幕后发生的事情吗?以及 Silverlight 客户端 UI 上的 Binding 属性如何与 C# 类保持联系,如果我错了,请纠正我,该类仍在下载 silverlight UI 的服务器上。

感谢您的宝贵时间。

最佳答案

如果 Person 类在同一个 Silverlight UI 项目中,那么它实际上是在客户端(而不是服务器)上。也许这样更容易理解?

关于c# - 如何将 Silverlight UI 绑定(bind)到 .NET 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3264396/

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