I want to bind a custom object to a usercontrol via XAML :
I have a MainPage and a user control. The model object :
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
MainPage :
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
public class MainPageViewModel : INotifyPropertyChanged
{
public MainPageViewModel()
{
TestToto = new Test() { Id = 1, Value = "A value" };
}
public event PropertyChangedEventHandler PropertyChanged;
private Test _test;
public Test TestToto
{
get { return _test; }
set { _test = value; NotifyPropertyChanged("TestToto"); }
}
protected void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
and the user control :
public sealed partial class MyUserControl1 : UserControl
{
public MyUserControl1()
{
this.InitializeComponent();
this.DataContext = this;
Debug.WriteLine($"ID =====================> {PropertyTest}");
}
public Test PropertyTest
{
get { return (Test)GetValue(PropertyTestProperty); }
set { SetValue(PropertyTestProperty, value); }
}
// Using a DependencyProperty as the backing store for PropertyTest. This enables animation, styling, binding, etc...
public static readonly DependencyProperty PropertyTestProperty =
DependencyProperty.Register("PropertyTest", typeof(Test), typeof(MyUserControl1), new PropertyMetadata(default(Test)));
}
In my MainPage.xaml, i create an instance of MyUserControl1 by binding dependencyproperty PropertyTest to TestToto (see MainPage.xaml.cs) :
<Grid>
<TextBox Grid.Row="1"
Text="{Binding TestToto.Value}" />
<local:MyUserControl1 Grid.Row="2"
PropertyTest="{Binding DataContext.TestToto, ElementName=maPage}" />
</Grid>
Here maPage is the name of MainPage page. Then in my user control's XAML i have :
<Grid>
<TextBox x:Name="textBox"
HorizontalAlignment="Left"
Margin="30,47,0,0"
TextWrapping="Wrap"
Text="{Binding PropertyTest.Value}"
VerticalAlignment="Top"
Width="146" />
</Grid>
The problem is that PropertyTest DP is always null :
First TextBox display Value property from MainPage and second Textbox should diplay the same.
For information, i follow this post from SO.
Thanks in advance
Regards