2012-06-01 73 views
0

我是新来的WPF,我试图绑定一个dependacy属性。 我想的是,我写上WPFCtrl文字:FilterTextBox将在TextBlock中无法绑定WPF DependencyProperty

在这里displaied是我的XAML

xmlns:WPFCtrl="clr-namespace:WPFControls" 
    xmlns:local="clr-namespace:WpfApplication9" 
    Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
    <local:Person x:Key="myDataSource" /> 
    </Window.Resources> 
    <Grid> 
    <StackPanel> 
    <StackPanel.DataContext> 
     <Binding Source="{StaticResource myDataSource}"/> 
    </StackPanel.DataContext> 
    <WPFCtrl:FilterTextBox Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged }"/> 
    <TextBlock Width="55" Height="25" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}"/> 
</StackPanel> 
</Grid> 

这里的人类

namespace WpfApplication9 
{ 
    public class Person : INotifyPropertyChanged 
    { 
     private string name = ""; 
     // Declare the event 
     public event PropertyChangedEventHandler PropertyChanged; 

     public Person() 
     { 
     } 

     public Person(string value) 
     { 
      this.name = value; 
     } 

     public string Name 
     { 
      get { return name; } 
      set 
      { 
       name = value; 
       // Call OnPropertyChanged whenever the property is updated 
       OnPropertyChanged("Name"); 
      } 
     } 

     // Create the OnPropertyChanged method to raise the event 
     protected void OnPropertyChanged(string name) 
     { 
      PropertyChangedEventHandler handler = PropertyChanged; 

      if (handler != null) 
      { 
       handler(this, new PropertyChangedEventArgs(name)); 

      } 
     } 
    } 
} 

和FilterTextBox文本属性

public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(FilterTextBox), new PropertyMetadata()); 

    public string Text 
    { 
     //get { return _tbFilterTextBox.Text == null ? null : _tbFilterTextBox.Text.TrimEnd(); } 
     get { return (string)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
     //set { _tbFilterTextBox.Text = value; } 
    } 

问题是它没有进入OnP ropertyChanged() 我在做什么错?

回答

1

这样做“FilterTextBox”控件每次插入文本时都会更新DP?

我想FilterTextBox有一个ControlTemplate里面有一个常规的TextBox。 像

<ControlTemplate TargetType="{x:Type FilterTextBox}"> 
<TextBox Name="PART_FilterTextBoxInputField" Text="{TemplateBinding Text}"/> 
</ControlTemplate> 

你需要设置的结合,其中内部文本框绑定到你的文字Dependcy物业使用UpdateSourceTrigger =的PropertyChanged了。否则绑定只会在文本框失去焦点时更新。

1

问题是FilterTextBox中的TextProperty默认情况下不绑定TwoWay

要么设置BindingModeTwoWay

<WPFCtrl:FilterTextBox Text="{Binding Path=Name, 
             Mode=TwoWay, 
             UpdateSourceTrigger=PropertyChanged }"/> 

或更改DependencyPropertyText的元数据,以便它在默认情况下结合双向

public static readonly DependencyProperty TextProperty = 
    DependencyProperty.Register("Text", 
           typeof(string), 
           typeof(FilterTextBox), 
           new FrameworkPropertyMetadata(null, 
        FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); 
相关问题