2016-01-24 100 views
0

我有文本框和我的用户控件,如何将文本框属性文本绑定到我的属性消息在UserControl中?将UIElement属性绑定到我的UserControl属性

XAML:

<TextBox Name="txtMessages"/> 

<myControl:MyAppBar x:Name="appBar" Message="{Binding ElementName=txtMessages, Path=Text, Mode=TwoWay}" Grid.Row="3"/> 

而且我的财产:

 public event PropertyChangedEventHandler PropertyChanged; 
     public void RaisePropertyChanged(string propertyName) 
     { 
      if (PropertyChanged != null) 
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
private string message; 
     public string Message 
     { 
      get 
      { 
       return message; 
      } 
      set 
      { 
       message = value; 
       RaisePropertyChanged("Message"); 
      } 
     } 

但是这对我来说不起作用。 我得到的错误为:

无法找到与此错误代码相关的文本。

而且我试试这个: 我尝试tihs:

public static readonly DependencyProperty UserControlTextProperty = DependencyProperty.Register(
     "Message", 
     typeof(int), 
     typeof(ImageList), 
     new PropertyMetadata(0, new PropertyChangedCallback(MyControl.MyAppBar.OnUserControlTextPropertyChanged)) 
     ); 

public string Message 
     { 
      get { return (string)GetValue(UserControlTextProperty); } 
      set { SetValue(UserControlTextProperty, value); } 
     } 

但unsver: “与此错误代码相关联的文本可能不会被发现。”

+1

你必须在你的UserControl中为Message注册一个'DependencyProperty':https://msdn.microsoft.com/library/system.windows.dependencyproperty(v=vs.110).aspx –

+0

@FlatEric更新问题 – user3588235

+1

您正在注册它为所有者类型'ImageList',但您的控件似乎是'MyAppBar'类型。而依赖项属性类型是'int',而CLR属性类型是'string' –

回答

1

首先,定义您自己的DependencyProperty需要保持命名规则。在上面的代码中,“UserControlTextProperty”不被识别为属性名称应该是“属性”+属性,如“MessageProperty”。

public static readonly DependencyProperty MessageProperty = DependencyProperty.Register("Message", typeof(int), typeof(ImageList), new PropertyMetadata(0, new PropertyChangedCallback(MyControl.MyAppBar.OnUserControlTextPropertyChanged))); 

public string Message 
{ 
    get { return (string)GetValue(MessageProperty); } 
    set { SetValue(MessageProperty, value); } 
} 

它将被识别为常规依赖项属性。 如果您正在自己的用户控件中编写代码,则不必将其ViewModel分开,而是让您的控件实现INotifyPropertyChanged接口并将控件的DataContext绑定到它自己。

相关问题