我创建了一个 UserControl,它有一个名为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); }
}
}
我在这样的窗口中使用这个 UserControl:
<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>
现在要获得 Hero 值,我使用这个:
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);
}
}
我可以访问Hero,因为我在 XAML 声明中为该 UserControl 指定了一个名称x:Name="Superhero"
,但是如果我删除 Name 属性,我如何访问该值?
我的意思是:如何使用某种绑定Hero
将值存储在值中!Human