2012-03-29 51 views
0

我不明白为什么我的大型项目中的绑定更改将无法正常工作。我已将其简化为一个仍不起作用的示例项目。如果可能的话,我想继续按照我现在的方式设置数据上下文,因为这是另一个项目的做法。使用以下代码,文本框中不显示SomeText中的文本。我该如何解决?基本Silverlight绑定

代码背后:

public partial class MainPage : UserControl 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 
     DataContext = new ViewModel(); 
    } 
} 

数据类:

public class ViewModel 
{ 
    public string SomeText = "This is some text."; 
} 

主要用户控制:

<UserControl xmlns:ig="http://schemas.infragistics.com/xaml"   x:Class="XamGridVisibilityBindingTest.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:XamGridVisibilityBindingTest="clr-namespace:XamGridVisibilityBindingTest" mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Grid x:Name="LayoutRoot" Background="White"> 
     <TextBox Text="{Binding SomeText}" BorderBrush="#FFE80F0F" Width="100" Height="50"> </TextBox> 
    </Grid> 
</UserControl> 

编辑:我只是试图做一个双向绑定。

回答

2

你需要使用属性,让你的虚拟机从INotifyPropertyChanged的继承和提高PropertyChanged事件时SomeText变化:

public class ViewModel : INotifyPropertyChanged 
{ 
    private string someText; 

    public event PropertyChangedEventHandler PropertyChanged; 

    public string SomeText 
    { 
     get { return someText; } 
     set 
     { 
      someText = value; 
      if (PropertyChanged != null) 
      { 
       PropertyChanged(this, new PropertyChangedEventArgs("SomeText")); 
      } 
     } 
    } 

    public ViewModel() 
    { 
     SomeText = "This is some text."; 
    } 
} 
+0

这会工作,但我只需要1路绑定。 – 2012-03-30 14:40:06

0

我想通了,你只能绑定属性!

public class ViewModel 
{ 
    public string SomeText { get; set; } 

    public ViewModel() 
    { 
     SomeText = "This is some text."; 
    } 
}