2017-11-15 5 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}}" –

관련 문제