2017-11-15 1 views
0

私は現在、オブジェクトのコレクションにバインドされたListBoxを持っており、コレクション内の各オブジェクトのボタンを表示しています。C#WPFバインディングパスが機能しない

XAML:ここ

<Window.DataContext> <local:MainWindowViewModel/> </Window.DataContext> <ListBox x:Name="company_buttons" HorizontalContentAlignment="Left" VerticalContentAlignment="Top" Padding="-2,-2,0,0" Height="280" Width="300" Background="{x:Null}" BorderBrush="{x:Null}" Margin="0,0,0,0" BorderThickness="0" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Buttons_Binding}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <Button Background="#FFFCC515" Style="{StaticResource RoundCorner}" FontFamily="Segoe UI" FontSize="16" FontWeight="Bold" TabIndex="0" CommandParameter="{Binding This_Works}" Command="{Binding HELP WITH THIS}"> <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="44"> <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/> <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/> </StackPanel> </Button> <Label VerticalContentAlignment="Top" Margin="5,0,5,0" Height="19" Padding="0" Foreground="White" FontFamily="Segoe UI" FontSize="12" FontWeight="Bold" Content="{Binding Path}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

は、バインディングで使用されているものがあります:

public class ButtonContent : INotifyPropertyChanged 
{ 
// stuff 
} 

public class MainWindowViewModel 
{ 
    public static ObservableCollection<ButtonContent> Buttons_Binding 
    { 
// stuff 
    } 

    public ICommand Command 
    { 
// stuff 
    } 

私の問題は、私はそれ以来Commandにボタンのクリックをバインドする方法がわからないですコレクションButtons_Bindingの外にあり、したがって同じデータコンテキスト内にありません。私が例から見たものと私が試したものはすべて失敗しました。

答えて

1

各ボタンはListBoxItemのDataContextにバインドされているため、ListBoxのDataContextにアクセスすることはできません。ただし、バインディングでRelativeSourceを使用してビジュアルツリーを走査できます。試してみてください

<Button ... 
     Command="{Binding Path=DataContext.Command, 
        RelativeSource={RelativeSource AncestorType=ListBox}}"> 
    ... 
</Button> 
+0

これはうまくいきました。何らかの理由で、私は検索で答えを見つけることができました。私はそれを機能させるために本当に不器用な方法を見つけました。私は関数を静的にしてからこれを行いました: 'Command =" {Binding Source = {x:Static local:MainWindowViewModel.Command}} " –

関連する問題