无法将DependencyProperty绑定到我的UserControl

时间:2012-04-02 16:35:28

标签: wpf xaml mvvm

我有下一个问题:我有一个视图:

<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock>
            test
            <TextBlock Text="{Binding TestingTest}"></TextBlock>
            test
        </TextBlock>
    </Grid>
</UserControl>

代码隐藏:

    public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public string TestingTest
    {
        get { return (string)GetValue(TestingTestProperty); }
        set { SetValue(TestingTestProperty, value); }
    }

    public static readonly DependencyProperty TestingTestProperty =
        DependencyProperty.Register("TestingTest", typeof(string), typeof(UserControl1), new UIPropertyMetadata("testing test"));

}

我尝试在ViewModel的视图中使用此视图:

<Window x:Class="WpfApplication1.MainWindow" Name="wnd" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525">
<Grid>
    <WpfApplication1:UserControl1 TestingTest="{Binding ElementName=wnd, Path=Title}"></WpfApplication1:UserControl1>
</Grid>

视图模型:

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    public string GoGoGo
    {
        get
        {
            return "Test message";
        }
    }
}

但每次我在“输出”窗口中收到下一条消息时都看不到测试消息:

* System.Windows.Data错误:40:BindingExpression路径错误:在'object'''UserControl1'(Name ='my')'上找不到'TestingTest'属性。 BindingExpression:路径= TestingText; DataItem ='UserControl1'(Name ='my'); target元素是'TextBlock'(Name =''); target属性是'Text'(类型'String') *

我错了什么?

1 个答案:

答案 0 :(得分:1)

这是一个错字。

在您的UserControl上,您拥有属性TestingTest,在WPF上有TestingText('s'和'x')