M.Azad M.Azad - 4 years ago 68
C# Question

How to bind a property from my usercontrol content control to a property in my viewmodel?

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 this control in a View such as MainWindowView
How can I Binde my Ytextbox Text Property to a property in my MainWindowViewModel?

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


I know that I must define a
DependencyProperty
for my control until I can bind a property in my viewmodel to it so i define a dependency property for my control like this:

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);
}
}


When I define a dependency property for my control I have a xaml error:


Error 1 Cannot create an instance of "customtextbox".

Answer Source
new FrameworkPropertyMetadata(false)

You cannot set the default value of a string property to false (which of course is a bool).

There may be some other problems (e.g. you have no binding on the TextBox in the user coontrol declaration and you try to set a property you did not register where you create an instance) but for those you should search SO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download