从另一个UserControl访问UserControl属性

时间:2013-11-14 09:11:54

标签: c# wpf mvvm user-controls dependency-properties

我创建了一个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); }
    }
}

我在这样的Window中使用这个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声明x:Name="Superhero"中为该UserControl命名,但是如果删除Name属性,如何访问该值?< / p>

我的意思是:如何使用某种绑定将Hero值存储在Human值中!

1 个答案:

答案 0 :(得分:2)

只需Bind您的Human媒体资源即可获得您控件中的Hero媒体资源:

<wpfApplication1:UcHeros Hero="{Binding Human, Mode=OneWayToSource}" />

如果您只想阅读该值而不更新它,请尝试使用OneWayToSource Binding


更新&gt;&gt;&gt;

正如@Killercam建议的那样,尝试在声明中设置属性的默认值而不是构造函数:

public static readonly DependencyProperty HeroProperty = DependencyProperty.
    Register("Hero", typeof(string), typeof(UcHeros), 
    new PropertyMetadata("Spiderman"));

如果仍然不起作用,那么你还有其他事情要做。