2011-12-14 40 views
3

我在试着了解XAML和代码隐藏如何彼此交谈。我知道,代码隐藏可以使用名称属性如访问XAML实例化的元素:使用XAML添加控件,但使用代码隐藏实例化

实例化XAML按钮:

<SomeControlParent controlParent> 
<Button Name=button1/> 
<SomeControlParent controlParent> 

按钮更改属性在后台代码:

button1.Content = "I created this button in XAML" 

我想知道是否有可能使用XAML例如做相反:

在实例化代码隐藏按钮:

Button button1 = new Button(); 
controlParent.Child.Add(button1); 

然后使用XAML更改按钮的内容。

谢谢! Soumaya

+0

+1新手有时会问最有趣的问题。这听起来像是一个基本的答案,但答案比你最初想象的要复杂。但是,这是雅的XAML。有很多新的概念要学习。 – HappyNomad 2011-12-14 19:41:23

回答

3

使用代码隐藏功能可以引用在XAML中定义了x:Name的元素。走向另一个方向,你可以在你的用户控件定义属性,然后使用的RelativeSource绑定引用它们在XAML:

{Binding MyProperty, RelativeSource={RelativeSource Self}} 
在你的榜样

所以,你可以有一个属性上的用户控件(虽然你可能会想这是一个依赖项属性所以你必须变更通知):

public Button Button1 { get; private set; } 

,然后用它插入到你的XAML:

<ContentControl Content={Binding Button1, RelativeSource={RelativeSource Self}}> 
    <ContentControl.Resources> 
     <Style TargetType="Button"> 
      <Setter Property="Content" Value="Hey, I changed the name in XAML!"/> 
     </Style> 
    </ContentControl.Resources> 
</ContentControl> 
+0

感谢HappyNomad – SuMau 2011-12-14 17:53:11