2009-09-26 37 views
17

你能像这样绑定到一个局部变量吗?WPF绑定到本地变量

SystemDataBase.cs

namespace WebWalker 
{ 
    public partial class SystemDataBase : Window 
    { 
     private string text = "testing"; 
... 

SystemDataBase.xaml

<TextBox 
     Name="stbSQLConnectionString" 
     Text="{SystemDataBase.text}"> 
</TextBox> 

??

将文本设置为局部变量“text”

回答

0

不,它必须是可见的属性。

30

的模式是:

public string Text {get;set;} 

,并且绑定是

{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}} 

如果你希望绑定自动更新你应该让一个DependencyProperty。


我觉得3.5加ElementName到绑定,所以下面是更容易一些:

<Window x:Name="Derp" ... 
    <TextBlock Text="{Binding Text, ElementName=Derp}"/> 
+3

还是有类执行INotifyPropertyChanged自动具有约束力的工作。 – 2009-09-27 18:39:51

+1

我想你的意思是把它改为DependencyProperty。在DependencyObject上实现INPC将是愚蠢的。 – Will 2009-11-27 18:24:31

+7

+1 for derp!大声笑 – windowskm 2012-06-29 14:23:14

22

要结合当地的 “变量” 的变量应该是:

  1. 一财产,而不是一个领域。
  2. 公共。
  3. 无论是通知属性(适用于模型类)或依赖属性(sutable为视图类)

例子:

public MyClass : INotifyPropertyChanged 
{ 
    private void PropertyType myField; 

    public PropertyType MyProperty 
    { 
     get 
     { 
      return this.myField; 
     } 
     set 
     { 
      if (value != this.myField) 
      { 
       this.myField = value; 
       NotifyPropertyChanged("MyProperty"); 
      } 
     } 
    } 

    protected void NotifyPropertyChanged(String propertyName) 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
} 

public MyClass : DependencyObject 
{ 
    public PropertyType MyProperty 
    { 
     get 
     { 
      return (PropertyType)GetValue("MyProperty"); 
     } 
     set 
     { 
      SetValue("MyProperty", value); 
     } 
    } 

    // Look up DependencyProperty in MSDN for details 
    public static DependencyProperty MyPropertyProperty = DependencyProperty.Register(...); 
} 
12

如果你做了很多这方面,你可以考虑将整个窗口的DataContext绑定到你的类。默认将被继承,但是仍然可以覆盖照常

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"> 

然后为各个组件可以使用

Text="{Binding Text}" 
+0

我知道这个问题是针对WPF的,但是如果你的目标是Silverlight,那么这就是要走的路。因为针对Web和Phone的Silverlight没有针对RelativeSource的FindAncestor方法 – Adarsha 2012-08-07 04:56:46

0

要绑定一个局部变量,它存在于你的窗口类有成为: 1.公共财产 2.通知财产。为此,您的窗口类应该为此属性实现INotifyPropertyChanged接口。

然后在构造函数中

public Assgn5() 
{   
    InitializeComponent(); 

    this.DataContext = this; // or **stbSQLConnectionString**.DataContext = this; 
} 

<TextBox 
    Name="stbSQLConnectionString" 
    Text="{Binding text}"> 
</TextBox>