Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML: Update binding when changing DataContext

I have a simple XAML file, it contains a Label whose Foreground property contains a binding:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="200" Height="100" >
    <Label Content="Sampletext" Foreground="{Binding Path=Color}" />
</Grid>

When I load the template and apply a DataContext the Foreground still has the default value. Is it possible to get bound foreground value without rendering the Grid?

// Load template
string templatePath = "/WpfApplication1;component/Template.xaml";
Grid grid = Application.LoadComponent(new Uri(templatePath, UriKind.Relative)) as Grid;

// Set dataContext
grid.DataContext = new { Color = Brushes.Green };

// Foregound still has default value
var foreground = ((Label)grid.Children[0]).Foreground;

Project can be downloaded here: http://dl.dropbox.com/u/21096596/WpfApplication1.zip

like image 354
Daniel Avatar asked Dec 09 '25 03:12

Daniel


1 Answers

try

lblName.GetBindingExpression(Label.ForegroundProperty).UpdateTarget();

before

var foreground = ((Label)grid.Children[0]).Foreground;
like image 191
Zahid Sattar Avatar answered Dec 10 '25 17:12

Zahid Sattar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!