2014-07-03 118 views
-5

有谁知道如何将字符串分配给文本块?如何将字符串分配给TextBlock?

e.x.我有一个字符串,可变内容和一个textBlock。 textBlock的文本应该总是匹配字符串的内容。

string number; 

public MainPage() 
{ 
    //the textBlock text should now be "1" 
    number = "1"; 

    //the textBlock text should now be "second" 
    number = "second"; 
} 

我尝试使用绑定自动执行此操作,但找不到解决方案。

问候, 克里斯蒂安

+4

为什么不使用['TextBlock.Text'](http://msdn.microsoft.com/en-us/library/ system.windows.controls.textblock.text(v = vs.110).aspx)属性 – Habib

+0

我已经使用过了,但是在字符串的每次更改下编写它非常麻烦。 – Cristian126

+1

为你的字符串定义一个私有属性,它是setter,将值设置为你的'TextBlock.Text',这是你可以模仿它的。 – Habib

回答

2

数据绑定工作,你需要有一个属性,不仅仅是一个简单的成员变量。而你的Datacontext类必须实现INotifyPropertyChanged接口。

public class MyDataContext : INotifyPropertyChanged 

    private string number; 
    public string Number { 
     get {return number;} 
     set {number = value; NotifyPropertyChanged("Number");} 
    } 

// implement the interface of INotifyPropertyChanged here 
// .... 
} 


public class MainWindow() : Window 
{ 
    private MyDataContext ctx = new MyDataContext(); 

    //This thing is out of my head, so please don't nail me on the details 
    //but you should get the idea ... 
    private void InitializeComponent() { 
     //... 
     //... some other initialization stuff 
     //... 

     this.Datacontext = ctx; 
    } 

} 

你可以使用这个在XAML如下

<Window ...> 
    <!-- some other controls etc. --> 
    <TextBlock Text={Binding Number} /> 
    <!-- ... --> 
</Window> 
+0

请注意,为此,您需要分配给“号码”而不是“号码”。显示绑定字符串设置也将使这个更好的答案。 +1为正确的方法。 – BradleyDotNET

+0

感谢您的评论。我根据你的建议编辑了我的答案。这不是最漂亮的解决方案,但应该有这个想法。 – derpirscher

+0

它看起来好多了,谢谢你的回应! – BradleyDotNET

相关问题