![](/img/trans.png)
[英]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.