2012-02-27 86 views
3

工作,我已經創建的樣本用戶控制動態與用戶綁定,靜態就是在Silverlight和MVVM

RestrictedBox.xaml

<UserControl.Resources> 
     <Converters:EnumToVisibilityConverter x:Key="enumToVisConverter" /> 
     <Converters:EnumToVisibilityConverterReverse x:Key="enumToVisConverterReverse" /> 
    </UserControl.Resources> 
    <Grid x:Name="LayoutRoot" Background="White" Width="Auto"> 
     <StackPanel Margin="0"> 
      <TextBox Text="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverter}}" BorderBrush="Green" /> 
      <PasswordBox Password="{Binding Value}" Visibility="{Binding Type,Converter={StaticResource enumToVisConverterReverse}}" BorderBrush="Red" /> 
     </StackPanel> 
    </Grid> 

RestrictedBox.xaml.cs器不起作用

public partial class RestrictedBox : UserControl 
    { 
     public RestrictedBox() 
     { 
      InitializeComponent(); 
      //If i bind static value and uncomment following line then it is working. 
      //If i bind static value and comment following line then it is not working 
      this.DataContext = this; 
      //Dynamic binding does not work using this code. 
     } 

     public string Value 
     { 
      get { return (string)GetValue(ValueProperty); } 
      set { SetValue(ValueProperty, value); } 
     } 
     public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(RestrictedBox), new PropertyMetadata("", ValueChanged)); 
     private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
     } 
     public Mode Type 
     { 
      get { return (Mode)GetValue(TypeProperty); } 
      set { SetValue(TypeProperty, value); } 
     } 
     public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(Mode), typeof(RestrictedBox), new PropertyMetadata(TypeChanged)); 
     private static void TypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
     } 
    } 

LoginViewModel.cs

public class LoginViewModel : INotifyPropertyChanged, IRegionMemberLifetime 
{ 
     private string _UserName = "Imdadhusen Sunasara"; 
     public string UserName 
     { 
      get { return _UserName; } 
      set 
      { 
       _UserName = value; 
       OnPropertyChanged("UserName"); 
      } 
     } 
} 

LoginView.xaml這下面的行不綁定工作)

<control:RestrictedBox Value="{Binding UserName}" Type="Text" /> 

這是工作與靜態結合

<control:RestrictedBox Value="Imdadhusen" Type="Text" /> 

Th anks, Imdadhusen

+0

首先,我看到你有很多的問題,瞭解什麼綁定。例如,沒有像「靜態綁定」這樣的東西。綁定只能是「動態」的。我幾乎不可能推薦Mattew McDonald的書「C#中的Pro Silverlight 4」 - 只讀一次,您將節省大量時間。 – chopikadze 2012-02-27 14:04:45

回答

2

其實它應該工作。您可以請驗證下面的控件的父容器的DataContext沒有引用viewmodel的任何其他屬性。

<control:RestrictedBox Value="Imdadhusen" Type="Text" /> 

例如,像下面的東西。

<StackPanel DataContext={Binding CurrentUser}> 

<control:RestrictedBox Value="{Binding UserName}" 

Type="Text" /> 

</StackPanel> 

可能是這個幫助你....