如何将我的usercontrol内容控件中的属性绑定到我的viewmodel中的属性?

时间:2011-10-31 12:05:22

标签: c# wpf xaml mvvm user-controls

我有这样的用户控件:

<UserControl x:Class="MySample.customtextbox"
         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="20" d:DesignWidth="300">
    <Grid>
           <TextBox x:Name="Ytextbox"  Background="Yellow"/> 
    </Grid>
</UserControl>

我想在一个View中使用此控件,例如MainWindowView 如何将我的Ytextbox文本属性存入我的MainWindowViewModel中的属性?

<CT:customtextbox  Text="{binding  mypropertyinviewmodel}"/>

我知道我必须为我的控件定义DependencyProperty,直到我可以将viewmodel中的属性绑定到它,所以我为我的控件定义了一个依赖属性,如下所示:

public static readonly DependencyProperty InfoTextProperty = 
        DependencyProperty.Register("InfoText", typeof(string), typeof(customtextbox), new FrameworkPropertyMetadata(false));

public string InfoText
{
    get { return (string)GetValue(InfoTextProperty);}
    set
    {
        SetValue(InfoTextProperty, value); 
    }
} 

当我为我的控件定义依赖项属性时,我有一个xaml错误:

  

错误1无法创建“customtextbox”的实例。

3 个答案:

答案 0 :(得分:2)

new FrameworkPropertyMetadata(false)

您无法将string属性的默认值设置为false(当然是bool)。

可能还有其他一些问题(例如,您对用户coontrol声明中的TextBox没有约束力,并且您尝试设置未在创建实例的位置注册的属性)但是对于那些应该搜索的问题SO。

答案 1 :(得分:1)

您正尝试将布尔值设置为字符串DependencyProperty。应该是那样的

 new FrameworkPropertyMetadata(string.Empty)

new FrameworkPropertyMetadata(null)

答案 2 :(得分:0)

请尝试将此作为依赖项属性的代码。

public static readonly DependencyProperty InfoTextProperty = 
    DependencyProperty.Register(
        "InfoText",
        typeof(string),
        typeof(customtextbox)
    );

    public string InfoText
    {

        get { return (string)GetValue(InfoTextProperty);}
        set {SetValue(InfoTextProperty, value); }
    } 

我刚从注册属性时删除了最后一个参数,我认为应该为属性提供默认值,而你提供的是布尔值而不是字符串,无论如何它都是可选参数。