【发布时间】:2011-10-31 12:05:22
【问题描述】:
我有一个这样的用户控件:
<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>
我想在诸如 MainWindowView 之类的视图中使用此控件 如何将 Ytextbox 文本属性绑定到 MainWindowViewModel 中的属性?
<CT:customtextbox Text="{binding mypropertyinviewmodel}"/>
我知道我必须为我的控件定义一个DependencyProperty,直到我可以将我的视图模型中的一个属性绑定到它,所以我为我的控件定义一个依赖属性,如下所示:
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”的实例。
【问题讨论】:
标签: c# wpf xaml mvvm user-controls