Skip to content

Instantly share code, notes, and snippets.

@dschenkelman
Created May 9, 2014 05:01
Show Gist options
  • Save dschenkelman/714725b67ed06edb2436 to your computer and use it in GitHub Desktop.
Save dschenkelman/714725b67ed06edb2436 to your computer and use it in GitHub Desktop.
Binding to View Model properties in Data Templates. The RootBinding Markup Extension
public class RootBindingExtension : IMarkupExtension<Binding>
{
public string Path { get; set; }
public Binding ProvideValue(IServiceProvider serviceProvider)
{
IRootObjectProvider rootProvider = (IRootObjectProvider) serviceProvider.GetService(typeof(IRootObjectProvider));
var view = rootProvider.RootObject;
var fe = view as FrameworkElement;
if (fe == null)
{
throw new InvalidOperationException("Root element must have data context");
}
var binding = new Binding();
binding.Path = new PropertyPath(this.Path);
binding.Source = fe.DataContext;
return binding;
}
}
<Grid x:Name="LayoutRoot" Background="White">
<ListBox ItemsSource="{Binding Names}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}"/>
<Button Content="{current:RootBinding Path=ButtonContent}" Command="{current:RootBinding Path=MessageBoxCommand}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment