2010-10-31 100 views
0

说我有XAML像WPF:绑定无法正常工作

<TabControl Grid.Row="1" Grid.Column="2" ItemsSource="{Binding Tabs}" IsSynchronizedWithCurrentItem="True"> 
    <TabControl.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding TabTitle}" /> 
     </DataTemplate> 
    </TabControl.ItemTemplate> 
    <TabControl.ContentTemplate> 
     <DataTemplate> 
      <local:UserControl1 Text="{Binding Text}" /> 
     </DataTemplate> 
    </TabControl.ContentTemplate> 
</TabControl> 

我要问哪里的TabTitleText性从何而来?我认为应该来自Tabs的每一项权利?说标签是ObservableCollection<TabViewModel>TabTitle & Text应该从TabViewModel属性权利。但在某种程度上似乎是正确的。 TabTitle正确填充,而Text不正确。

TextUserControl1如下

public string Text 
{ 
    get { return (string)GetValue(TextProperty); } 
    set { SetValue(TextProperty, value); } 
} 

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

当我有没有绑定到ObservableCollection<TabViewModel>绑定选项卡工作正常

<TabControl Grid.Row="1" Grid.Column="1"> 
    <TabItem Header="Tab 1"> 
     <local:UserControl1 Text="Hello" /> 
    </TabItem> 
    <TabItem Header="Tab 2"> 
     <local:UserControl1 Text="World" /> 
    </TabItem> 
</TabControl> 
+0

检查输出窗口是否存在绑定错误 – benPearce 2010-10-31 04:59:22

+0

您是否使用某个值初始化TabViewModel.Text?或者它是空的?另外,您的TabViewModel是否实现INotifyPropertyChanged接口? – Nawaz 2010-12-01 06:19:10

回答

0

如果从暴食用户控件的属性代码隐藏文件,你应该使用

{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text} 

直接绑定只适用于DataContext

0

我想我知道是什么问题声明为一个依赖属性。 UserControl1中的元素(应该由Text属性填充)不会观察此属性的更改。因此,有两种方式:

1)使用PropertyChangedCallback:

public static readonly DependencyProperty TextProperty = 
DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata(""), 
    new PropertyChangedCallback(OnTextPropertyChanged)); 

private static void OnTextPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) 
{ 
    ((UserControl1)sender).OnTextChanged(); 
} 

private void OnTextChanged() 
{ 
    this.myTextBlock.Text = this.Text; 
} 

2)整蛊绑定:

<UserControl x:Class="UserControl1" x:Name="root" ...> 
... 
    <TextBlock Text="{Binding Text, ElementName=root}"/> 
... 
</UserControl> 
+0

嗯...这仍然不起作用,没有任何错误寿。我还认为'DependencyProperty.Register'的语法是'public static readonly DependencyProperty TextProperty = DependencyProperty.Register(“Text”,typeof(string),typeof(UserControl1),new UIPropertyMetadata(“”,new PropertyChangedCallback(OnTextChanged))) ;' – 2010-11-02 08:07:34

+0

将一个断点放入TextChanged处理程序并检查属性的值。 – vorrtex 2010-11-03 21:48:10