2011-05-12 224 views
5

我有一個視圖模型,它繼承自一個名爲IsReadOnly屬性的基類。 在這個視圖模型中,我有一個名爲Customer的屬性,我將客戶對象的屬性綁定到我的視圖上的控件。MVVM綁定屬性和子屬性

但是我也希望能夠將IsReadOnly綁定到我的視圖上的每個控件。

<TextBox x:Name="FirstNameTextBox" Grid.Column="1" Margin="2,2,0,2" Grid.Row="2" TextWrapping="Wrap" HorizontalAlignment="Left" Width="200" 
         Text="{Binding FirstName, Mode=TwoWay}" IsReadOnly="{Binding MyViewModel.IsReadOnly}"/> 

我該如何去使用這兩個屬性? 這裏是我的結構

公共類MyViewModelBase { 公共BOOL IsReadonly {獲得;設置;}}

公共類MyViewModel { 公衆客戶客戶{獲得;組; } }

公共類客戶{ public string FamilyName {get;組; } }

乾杯任何幫助

回答

0

我假設你的MyViewModel繼承自MyViewModelBase。

public class MyViewModelBase { public bool IsReadonly { get;set;} } 

public class MyViewModel : MyViewModelBase { public Customer Customer { get; set; } } 

public class Customer { public string FamilyName { get; set; } } 

我也認爲你的觀點的DataContext是MyViewModel的一個實例,如果不是讓我知道:)你的結合應該是這樣的:

<TextBox x:Name="FirstNameTextBox" Grid.Column="1" Margin="2,2,0,2" Grid.Row="2" TextWrapping="Wrap" HorizontalAlignment="Left" Width="200" 
     Text="{Binding Customer.FamilyName, Mode=TwoWay}" IsReadOnly="{Binding IsReadOnly}"/> 

編輯:如果你的TextBox的DataContext的是客戶財產,你必須使用RelativeSource綁定到IsReadOnly

+0

謝謝,這解決了我的問題。很高興知道你可以做房產遍歷。 :) – BBurke 2011-05-12 12:47:50

7

物業穿越工程與綁定,所以你可以做以下綁定到基本對象的IsReadOnly屬性:

public class MyViewModel { 
    public Customer Customer { get; set; } 
} 

public class Customer : Entity { 
} 

public class Entity { 
    public bool IsReadonly { get;set;} 
} 

<Button IsEnabled="{Binding Customer.IsReadonly}" /> 

對於上面的例子,我假設你的視圖綁定到「MyViewModel」的實例,並且你的屬性可能已經有屬性通知的改變。

+0

嗨哈迪,我明白你的意思了。所以我將我的客戶綁定到一個Grid的DataContext,並且在Grid中我有TextBoxes綁定到Customer屬性。但我也想將IsEditable,IsReadOnly綁定到viewModel的IsReadOnly屬性。可能嗎? – BBurke 2011-05-12 08:55:50