2011-08-30 48 views
1

Windows Phone應用程序(Silverlight 3中)綁定到不同的dataContexts

我有一個文本塊

TextBlock的
<TextBlock Text="{Binding Key}" FontSize="40" Foreground="{Binding propertyOnAMainViewModel}" /> 

DataContext設置一類組實例,暴露出關鍵屬性。

我需要將TextBlock的前景屬性綁定到動態(可從代碼設置)屬性,但是在不同的ViewModel上,而不是組。

是否有可能將一個元素的不同屬性綁定到不同的數據上下文?

回答

2

你可以做到這一點,但它不是非常優雅!每個綁定都有一個Source,如果未指定,則爲控件的DataContext。如果您在代碼隱藏中構建綁定,則可以明確設置源。在XAML中,唯一的選項是默認的(即DataContext)或ElementName綁定。

我會做的是創建一個ViewModel,公開您想要綁定到的兩個屬性,並將其用作DataContext

0

這是最簡單的,如果你可以承載一個VM的另一個內:

public class TextBoxViewModel : ViewModelBase 
{ 
    private ChildViewModel _childVM; 

    public ChildViewModel ChildVM 
    { 
    get { return _childVM; } 
    set 
    { 
     if (_childVM == value) 
     return; 

     if (_childVM != null) 
     _childVM.PropertyChanged -= OnChildChanged; 

     _childVM = value; 

     if (_childVM != null) 
     _childVM.PropertyChanged += OnChildChanged; 

     OnPropertyChanged("ChildVM"); 
    } 
    } 

    public Brush TextBoxBackground 
    { 
    get 
    { 
     if(ChildVM == null) 
     return null; 

     return ChildVM.MyBackground; 
    } 
    set 
    { 
     if (ChildVM != null) 
     ChildVM.MyBackground = value; 
    } 
    } 

    private void OnChildChanged(object sender, PropertyChangedEventArgs e) 
    { 
    if (string.IsNullOrEmpty(e.PropertyName) || e.PropertyName == "MyBackground") 
     OnPropertyChanged("TextBoxBackground"); 
    } 
}