Reputation: 9384
I have a WPF-Application with a Window
and a UserControl
. The UserControl
is implemented with the MVVM-Pattern. So in the view I have a Label
which displays the value of a string
-property called InfoMessage in the ViewModel.
In the Window
I added an instance of this UserControl
by
<views:ItemInfoView Grid.Row="3" Grid.Column="1" x:Name="itemInfoView"/>
Now I want to set the InfoMessage from the XAML of my Window
. Currently I have no idea how to achieve this in xaml. In code-behind I could access the DataContext
of my control and cast it to ItemInfoViewModel and the set the value like:
((ItemInfoViewModel)itemInfoView.DataContext).InfoMessage = "Hello World";
But I hope there's a way to do this in pure XAML. Does anyone know if this is possible and how?
Upvotes: 1
Views: 431
Reputation: 10324
You need to add a Dependency Property to your user control:
// Your property
public string InfoMessage{get;set;}
// Register Dependency Property
public static readonly DependencyProperty InfoMessageProperty =
DependencyProperty.Register("InfoMessage", typeof(string), typeof(ItemInfoView),
new UIPropertyMetadata(true));
Then you should be able to just set or bind InfoMessage directly:
<views:ItemInfoView Grid.Row="3" Grid.Column="1" InfoMessage="Whatever"/>
Upvotes: 5