2011-12-22 209 views
1

我是WP7和.net編程領域的新手,我需要幫助。我有一個使用模板綁定的屬性的自定義組件。與模板綁定和自定義組件綁定的問題

<TextBlock Text="{TemplateBinding Info}" FontSize="20" Grid.Row="1" TextWrapping="{TemplateBinding TextWrap}"/> 

我在.cs文件中定義了依賴項屬性。

現在在我的page.xaml我把自定義組件,像這樣,

<rounded:RoundedImageView x:Name="pivotItem1" Info="Test bind" BorderBrush="White" ImageSrc="Images/default_service.png" TextWrap="Wrap"/> 

其中工程確定,現在我想的信息和TextWrap屬性動態基於一些外部變量,所以我做了這個改變

<rounded:RoundedImageView x:Name="pivotItem1" Info="{Binding sopInfo}" BorderBrush="White" ImageSrc="Images/default_service.png" TextWrap="{Binding wrap}"/> 

其中sopInfo渦卷在頁面的支持CS文件中定義的外部變量。但是這不起作用,Info和TextWrap值不會改變。我怎樣才能實現它? 感謝

回答

1

嘗試設置的DataContext你的頁面是這樣的:

<phone:PhoneApplicationPage 
     DataContext="{Binding RelativeSource={RelativeSource Self}}" /> 

然後確保sopInfowrap是公共的Page類的DependancyProperties

public static readonly DependencyProperty sopInfoProperty = 
    DependencyProperty.Register(
    "sopInfo", typeof(String), 
    ); 

public string sopInfo 
{ 
    get { return (string)GetValue(sopInfoProperty); } 
    set { SetValue(sopInfoProperty, value); } 
} 
+0

非常感謝!沒有其他方法嗎?它基本上意味着我必須有各地的依賴屬性! – 2011-12-22 06:19:19

+0

不幸的是,沒有。這是他應該如何在WPF中完成的。您可以嘗試並實現INotifyPropertyChanged,但您仍然需要在每個設置器中調用OnPropertyChanged。發生綁定時,WPF必須具有引發事件的機制,這就是爲什麼它需要DependancyProperty或INotifyPropertyChanged。 http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx – 2011-12-22 13:44:59