Binding to a different dataContexts
Windows Phone application (Silverlight 3)
I have a textblock
<TextBlock Text="{Binding Key}" FontSize="40" Foreground="{Binding propertyOnAMainViewModel}" />
DataContext of a TextBlock is set to a class Grou开发者_如何学Gop instance, that exposes Key property.
I need to bind the foreground property of the TextBlock to a dynamic (settable from code) property, but on a different ViewModel, not the Group.
Is it possible to bind different properties on one element to a different data contexts?
You can do this,, but it is not terribly elegant! each binding has a Source, which, if not specified, is the control's DataContext
. You can set the source explicitly if you construct the binding in code-behind. Within XAML, your only options are default (i.e. DataContext), or ElementName
bindings.
What I would do is create a ViewModel that exposes both the properties you wish to bind to, and use that as your DataContext
.
It's easiest if you can host one VM inside of another:
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");
}
}
精彩评论