2009-09-30 124 views
0

我在UserControl庫(單獨的程序集)中有一個Usercontrol。我在我的XAML標記是這樣的:如何將數據綁定到WPF Usercontrol中的屬性?

<UserControl x:Class="CenterTextTemplate.CenterTextTemplate" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Name="Test" 
Height="Auto" 
Width="Auto">  
<Grid> 
    <!--<TextBlock Name="TextField" Text="{Binding Text}"></TextBlock>  --> 
    <Viewbox VerticalAlignment="Center" 
      HorizontalAlignment="Center"> 
     <TextBlock Name="TextField" 
        Text="{Binding Text, ElementName=Test}" 
        Foreground="Red" FontSize="50"> 
     </TextBlock> 
    </Viewbox> 
</Grid> 

在我的.cs文件我有一個屬性:

public string Text { get { return "test"; } } 

當我加載用戶控件我沒有看到「測試」文字。 ..有什麼我失蹤?試圖給不給一個名稱的用戶控件,但沒有工作要麼...

編輯:

在此設置中我得到這個錯誤:

Error 1 The type name 'CenterTextTemplate' does not exist in the type 'CenterTextTemplate.CenterTextTemplate' C:\Documents and Settings\Brian Hvarregaard\My Documents\Visual Studio 2008\Projects\GreenWeb Templates\CenterTextTemplate\CenterTextTemplate.xaml 4 37 CenterTextTemplate

回答

0

您需要使用的依賴屬性綁定到一個屬性。請參閱link以及DependencyProperty的msdn頁面。

+0

使用CLR屬性綁定但我只希望當我創建的用戶控件的一個實例設置一次屬性 - 心不是dependencyproperties有點大材小用了點。我希望textblock所做的就是從屬性背後的「文本」代碼中獲取文本......就是這樣 – H4mm3rHead 2009-09-30 18:22:46

0

對於綁定,您必須將其設置爲DependencyProperty,否則您必須實現INotifyPropertyChanged接口。如果您不想採取任何行動,請不要使用綁定,而應直接分配值。

您可以通過使用BindingMode = OneWayToSource

相關問題