如何在WPF中绑定局部变量

时间:2010-06-21 04:18:15

标签: wpf xaml binding

我有silverlight用户控件。这包含服务实体对象。见下文

public partial class MainPage : UserControl
{
   public ServiceRef.tPage CurrentPage { get; set; }
...
}

我需要将CurrentPage.Title绑定到TextBox

我的xaml在这里

<TextBox Text="{Binding Path=CurrentPage.Title, RelativeSource={RelativeSource self}}"></TextBox>

但这不起作用。

怎么做?

3 个答案:

答案 0 :(得分:2)

为了实现这一目标,您必须在课堂上实施INotifyPropertyChanged并在PropertyChanged设置时CurrentPage举起事件(这也意味着您不会能够使用自动属性;您必须使用自己的私有实例支持变量并自己编写get { }set { }代码。

正在发生的事情是控件在设置CurrentPage之前绑定到该值。因为您没有通知任何人该属性已更改,所以它不知道刷新绑定数据。实施INotifyPropertyChanged将解决此问题。

或者您可以在设置器中自己手动设置Text属性。

答案 1 :(得分:0)

将您的标记更改为

<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=CurrentPage.Title}" />

通过分配RelativeSource={RelativeSource self},您告诉TextBlock绑定到自身,并在CurrentPage本身而不是父TextBlock上查找名为Window的属性}。

答案 2 :(得分:0)

在XAML中设置UpdateSourceTrigger="PropertyChanged"