[英]How to bind a property from my usercontrol content control to a property in my viewmodel?
[英]How to bind a property from my usercontrol content control to a property?
我有一个这样的UserControl:
<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>
我想在mvvm模式中使用我的控件...我希望我可以将viewmodel中的属性绑定到Ytextbox文本属性
<CT:customtextbox ?(Ytextbox)Text ="{binding mypropertyinviewmodel}"/>
...我该怎么做?
您应该在UserControl上创建一个属性,并将其内部绑定到TextBox的文本。
即
<UserControl Name="control" ...>
<!-- ... -->
<TextBox Text="{Binding Text, ElementName=control}"
Background="Yellow"/>
public class customtextbox : UserControl
{
public static readonly DependencyProperty TextProperty =
TextBox.TextProperty.AddOwner(typeof(customtextbox));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
用法:
<CT:customtextbox Text="{Binding mypropertyinviewmodel}"/>
(除非希望所有希望继承DataContext的外部绑定都失败,否则请不要将UserControl中的DataContext设置为自身,请使用ElementName
或RelativeSource
进行内部绑定)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.