Data binding 绑定到不同的DataContext
Windows Phone应用程序(Silverlight 3) 我有一个文本块Data binding 绑定到不同的DataContext,data-binding,windows-phone-7,mvvm,Data Binding,Windows Phone 7,Mvvm,Windows Phone应用程序(Silverlight 3) 我有一个文本块 <TextBlock Text="{Binding Key}" FontSize="40" Foreground="{Binding propertyOnAMainViewModel}" /> TextBlock的DataContext被设置为一个类组实例,该实例公开了Key属性 我需要将TextBlock的前台属性绑定到一个动态(可从代码设置)属性,但是绑定到另一个ViewModel,而不是组
<TextBlock Text="{Binding Key}" FontSize="40" Foreground="{Binding propertyOnAMainViewModel}" />
TextBlock的DataContext被设置为一个类组实例,该实例公开了Key属性
我需要将TextBlock的前台属性绑定到一个动态(可从代码设置)属性,但是绑定到另一个ViewModel,而不是组
是否可以将一个元素上的不同属性绑定到不同的数据上下文 你可以这样做,但它并不十分优雅!每个绑定都有一个源,如果未指定,则该源是控件的
DataContext
。如果在代码隐藏中构造绑定,则可以显式设置源代码。在XAML中,您唯一的选项是默认值(即DataContext)或ElementName
bindings
我要做的是创建一个ViewModel,公开您希望绑定到的两个属性,并将其用作您的
DataContext
如果您可以将一个VM托管在另一个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");
}
}