2010-03-23 55 views
2

我有一個自定義UserControl(例如)MyPanel,並且我想在另一個XAML文件中使用它。我想設置MyPanel,如入MyPanel放在XAML文件「標題」的屬性,如下所示:非常基本的Silverlight綁定問題

<UserControl x:Name="ContainerControl"> 
    <local:MyPanel Title="Whatever I Want" /> 
</UserControl> 

我想對於MyPanel的「標題」屬性,然後填充TextBlock在MyPanel中。 如何在MyPanel中設置代碼和/或XAML來支持這樣的屬性?

我甚至不確定這是否具有約束力,所以如果這是錯誤的,請原諒我的無知。

回答

2

我能想到的最簡單的解決方法是: -

MyPanel XAML: -

<UserControl x:Class="SilverlightApplication1.MyPanel" ...> 
    <Grid x:Name="LayoutRoot"> 
    <TextBlock x:Name="txtTitle" /> 
    <!-- other stuff here --> 
    </Grid> 
</UserControl> 

MyPanel.cs: -

public partial class MyPanel : UserControl 
{ 
    // constructor stuff here. 

    public string Title 
    { 
     get { return txtTitle.Text; } 
     set { txtTitle.Text = value; } 
    } 
} 

還有其他一些 「聰明」 的解決方案,但此對於這個要求已經足夠了。

+0

完美!回想起來很明顯。我擔心我需要使它成爲全面的DependencyProperty或其他。 – Klay 2010-03-23 19:47:45

+0

在這種情況下,不需要DependencyProperty,我更願意提供最簡單的解決方案。但是,如果您想重複使用「MyPanel」控件並將數據綁定到「Title」屬性,則需要將其作爲DependencyProperty實現。 – AnthonyWJones 2010-03-23 20:40:01