Reputation: 10983
I created a UserControl, which has a property called Hero
public partial class UcHeros : UserControl
{
public UcHeros()
{
InitializeComponent();
Hero = "Spiderman";
}
public static readonly DependencyProperty HeroProperty = DependencyProperty.Register("Hero", typeof(string), typeof(UcHeros), new PropertyMetadata(null));
public string Hero
{
get { return (string)GetValue(HeroProperty); }
set { SetValue(HeroProperty, value); }
}
}
I'm using this UserControl inside a Window like this :
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<wpfApplication1:UcHeros x:Name="Superhero" />
<Button Click="OnClick">Click</Button>
</StackPanel>
</Grid>
</Window>
Now to get the Hero value I use this :
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty HumanProperty = DependencyProperty.Register("Human", typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public string Human
{
get { return (string)GetValue(HumanProperty); }
set { SetValue(HumanProperty, value); }
}
private void OnClick(object sender, RoutedEventArgs e)
{
Debug.WriteLine(Superhero.Hero);
}
}
I can access to the Hero because I gived a name to that UserControl in my XAML declaration x:Name="Superhero"
, but how can I access to that value if I remove the Name property ?
I mean : How can I store the Hero
value in the Human
value using some sort of Binding !
Upvotes: 0
Views: 1615
Reputation: 69959
Just Bind
your Human
property to the Hero
property on your control:
<wpfApplication1:UcHeros Hero="{Binding Human, Mode=OneWayToSource}" />
Try using a OneWayToSource Binding
if you just want to read the value and not update it.
UPDATE >>>
As @Killercam suggested, try setting the default value for your property in the declaration instead of the constructor:
public static readonly DependencyProperty HeroProperty = DependencyProperty.
Register("Hero", typeof(string), typeof(UcHeros),
new PropertyMetadata("Spiderman"));
If that still doesn't work, then you've got something else going on there.
Upvotes: 2