在DataTemplate中訪問DataContext

原因:我在datatemplate中使用命令,這些命令全部來自於ViewModel中。這些命令卻始終無法生效,後來發現根本就沒有綁定上。查了很久發現datatemplate中是無法訪問到datatemplate控件層以外的資源,包括ViewModel中的命令。

原代碼:

        <ListBox Grid.Row="2" ItemsSource="{Binding OutPutFileList}" Background="GhostWhite">
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="10,10,10,10">
                        <TextBlock Text="{Binding CommitFile}" FontSize="16" Margin="0,0,15,0" Width="350px" />
                        <Button Content="複製" Command="{Binding CopyCommand}" CommandParameter="{Binding CommitFile}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
如上所示,CopyCommand是無法觸發的。

解決:爲了訪問到datacontext中的命令,我們需要改變命令源,通過指定父級來訪問全局的datacontext

代碼:

        <ListBox Grid.Row="2" ItemsSource="{Binding OutPutFileList}" Background="GhostWhite" x:Name="CommitList">
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Margin="10,10,10,10">
                        <TextBlock Text="{Binding CommitFile}" FontSize="16" Margin="0,0,15,0" Width="350px" />
                        <Button Content="複製"   Command="{Binding ElementName=CommitList,Path=DataContext.CopyCommand}" CommandParameter="{Binding CommitFile}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


啓發自鏈接:https://stackoverflow.com/questions/3404707/access-parent-datacontext-from-datatemplate/3547707#3547707




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章