2012-03-29 66 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."; 
    } 
}