TextBlock绑定?

时间:2012-03-29 05:28:34

标签: windows-phone-7

我在.cs

中添加代码
 public static readonly DependencyProperty lbStatusProperty =
        DependencyProperty.Register("lbStatus", typeof(string), typeof(SingleTalkView),
        new PropertyMetadata(""));

    public string lbStatus
    {
        get { return (string)GetValue(lbStatusProperty); }
        set { SetValue(lbStatusProperty, value); }
    }

in xaml

<TextBlock Text="{Binding lbStatus}" Style="{StaticResource PhoneTextNormalStyle}" Height="24"/>

然后添加全局值

private string a = "Test";

并在init函数中

this.lbStatus = a;

最后我添加了一个按钮并更改了一个值,TextBlock没有改变!为什么? THX ~~~~

2 个答案:

答案 0 :(得分:1)

.NET中的String是一种不可变类型。当您输入:

this.lbStatus = a;

将lbStatus设置为对a变量当前指向的字符串的引用。之后,当您更改:

a = "Foo";

您不会更改this.lbStatus,因为您要将a变量分配给一个全新的字符串实例。

答案 1 :(得分:0)

这可能有助于您更好地理解

public class Base : INotifyPropertyChanged
    {      
        public event PropertyChangedEventHandler PropertyChanged;       
        protected void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }       
    }

//ViewModel
public class ViewModel : Base
private string _value;
        public string value {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
                this.NotifyPropertyChanged("value");
            }
        }
//View
<Textbox Height="60" Width="60" Foreground="Wheat"
                         Text="{Binding value,Mode=TwoWay}" >