Reputation: 3763
I have a UserControl like this:
<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>
I want use my control in mvvm pattern ...i want that i can bind a property in my viewmodel to Ytextbox Text Property
<CT:customtextbox ?(Ytextbox)Text ="{binding mypropertyinviewmodel}"/>
...how can I do it?
Upvotes: 2
Views: 1159
Reputation: 184441
You should create a property on the UserControl and bind that internally to the TextBox's text.
i.e.
<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); }
}
}
Usage:
<CT:customtextbox Text="{Binding mypropertyinviewmodel}"/>
(Do not set the DataContext in the UserControl to itself unless you want all external bindings which expect the DataContext to be inherited to fail, use ElementName
or RelativeSource
for internal bindings)
Upvotes: 5