如何数据绑定到WPF Usercontrol中的属性?

时间:2009-09-30 17:56:37

标签: c# data-binding xaml

我在Usercontrol库中有一个UserControl(单独的程序集)。我的XAML标记就像这样:

<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"; } }

当我加载用户控件时,我看不到“测试”文本...有什么我缺少的吗?试图不给用户控件提供名称,但这不起作用......

编辑:

在此设置中,我收到此错误:

  

错误1类型中不存在类型名称“CenterTextTemplate”   'CenterTextTemplate.CenterTextTemplate'C:\ Documents and   设置\ Brian Hvarregaard \ My Documents \ Visual Studio   2008 \项目\ GreenWeb   Templates \ CenterTextTemplate \ CenterTextTemplate.xaml 4 37 CenterTextTemplate

2 个答案:

答案 0 :(得分:0)

您需要使用依赖项属性绑定到属性。请参阅此link以及DependencyProperty的msdn页面。

答案 1 :(得分:0)

对于Binding,您必须使其成为DependencyProperty,或者您必须实现INotifyPropertyChanged接口。如果你没有蚂蚁去任何一种方式,不要使用绑定,而是直接分配值。

您可以使用BindingMode = OneWayToSource

绑定CLR属性