Created
May 9, 2014 05:01
-
-
Save dschenkelman/714725b67ed06edb2436 to your computer and use it in GitHub Desktop.
Binding to View Model properties in Data Templates. The RootBinding Markup Extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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