ItemsSourceを設定した際、親のDataContextにバインドする
ListBoxでItemsSourceを設定すると、親のDataContextにバインドできなくなる。
やりたいこととしては、下に書いた方法で親DataContextのHeightにバインドしたい。
でも下の方法ではできない。
MainWindowViewmodel.cs
class WindowViewModel { public List<string> List { get; set; } public int Height { get; set; }
MainWindow.xaml
<Grid> <ListBox Grid.Column="2" ItemsSource="{Binding person}"> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="{Binding Height}" /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>
で、下の様にResourcesを設定してあげるとバインドできるようになる。
MainWindow.xaml
<Window.Resources> <vm:WindowViewModel x:Key="viewmodels" /> </Window.Resources> <Grid> <ListBox Grid.Column="2" ItemsSource="{Binding person}"> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="{Binding Height, Source={StaticResource viewmodels}}" /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions>