2009-12-16 61 views
1

我正在嘗試使具有IsReadOnly屬性的Address控件具有IsReadOnly屬性,該屬性將使每個TextBox僅在設置爲true時才被讀取。將屬性綁定到獨立於DataContext的Silverlight依賴項屬性

<my:AddressControl Grid.Column="1" Margin="5" IsReadOnly="True"/> 

我已經設法做到這一點,只要有依賴項屬性,它的工作原理。

這裏的依賴屬性的簡單類中聲明:

public partial class AddressControl : UserControl 
{ 
    public AddressControl() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 

    public static readonly DependencyProperty IsReadOnlyProperty = 
     DependencyProperty.Register("IsReadOnly", typeof(bool), 
            typeof(AddressControl), null); 

    public bool IsReadOnly 
    { 
     get { return (bool)GetValue(IsReadOnlyProperty); } 
     set { SetValue(IsReadOnlyProperty, value); } 
    } 
} 

在XAML此代碼隱藏文件,我爲每個地址線Textbox

<TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding City, Mode=TwoWay}"/> 
    <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding State, Mode=TwoWay}"/> 
    <TextBox IsReadOnly="{Binding IsReadOnly}" Text="{Binding Zip, Mode=TwoWay}"/> 

就像我說的這個工程只是精細。 問題是,Address控制本身綁定到它的父對象(我有幾個地址我綁定)。

<my:AddressControl DataContext="{Binding ShippingAddress, Mode=TwoWay}" IsReadOnly="True"> 
<my:AddressControl DataContext="{Binding BillingAddress, Mode=TwoWay}" IsReadOnly="True"> 

的問題是,當我設置DataContext'this'其他東西則IsReadOnly斷結合。不足爲奇,因爲它在Address數據實體上尋找IsReadOnly,並且它不存在或屬於那個數據實體。

我已經嘗試過幾乎所有binding attributes組合,以獲得IsReadOnly綁定到AddressControl obejct,但無法使其工作。

我試過這樣的事情,但我無法獲得IsReadOnly獨立綁定到AddressControl屬性,而不是它的DataContext

<TextBox IsReadOnly="{Binding RelativeSource={RelativeSource Self}, Path=IsReadOnlyProperty}" Text="{Binding City, Mode=TwoWay}" /> 

我覺得我很親密。我究竟做錯了什麼?

+0

玩過'Text'屬性的綁定工具後,似乎'RelativeSource Self'實際上意味着綁定到TextBox本身 - 這不是我想要的。因此,我認爲我需要FindAncestor,它在Silverlight中不存在:-(我認爲我卡住了?http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID = 480603 – 2009-12-16 12:58:16

回答

1

With this answer(實際上我自己對類似問題的回答)我有一個很好的[更好的]解決方案。

我仍然需要遍歷文本框,但我不必設置實際值。我可以在代碼隱藏中創建綁定,而不是使用XAML。

+0

就像說這是正確的方法,並且被標記的答案是錯誤的 - 這是可能的,而且你沒有被卡住。 – Quango 2011-08-12 10:10:58

+0

哦,我剛剛意識到這是我的問題,所以我可以改變答案。大聲笑 – 2011-08-12 21:22:00

+0

我認爲肯意味着你不能用XAML Bindings做到這一點 - 但幸運的是,它可能在代碼中創建一個綁定 – 2011-08-12 21:22:55

0

我覺得如果你只是想通過綁定來做到這一點,至少你會被卡住。我的猜測是,你將不得不求助於代碼隱藏,大概是通過迭代你的子文本框控件並將它們的IsReadOnly屬性設置爲Address控件的IsReadOnly屬性的副作用。

與一些認爲坐在代碼隱藏文件中的任何代碼實際上是承認失敗的人不同,我對此沒有信心:如果將代碼放入代碼隱藏是最簡單的方法這是我放置代碼的地方。相反,如果我必須花半天的時間試圖找出如何通過綁定來完成某些工作,那麼我可以在五分鐘內完成代碼隱藏,失敗,IMO。

+0

如果我堅持我發現 - 只是沒有想錯過什麼。這些學習體驗可以幫助您更好地理解框架,即使您最初確實浪費了一些時間。絕對同意在代碼背後的東西 - 見我的帖子在這裏http://stackoverflow.com/questions/489415/how-to-get-a-codebehind-file-for-an-asp-net-mvc-view -in-rc1-to-be-created-by-de – 2009-12-17 22:14:14