WPF中使用DataGrid后,里面的Button的Command不響應的問題


前一篇說了一個較為復雜的方案,以解決向外代理綁定的問題,上一篇的方案在WPF中是不適用的。現在可以提一個較為通用的方案,可以為WPF及SL共同解決的。方案很簡單。

 1 <DataGrid ItemsSource="{Binding Path=AccountStore}">
 2             <DataGrid.Columns>
 3                 <DataGridTextColumn Header="賬戶名稱" Binding="{Binding Path=AccountName}"/>
 4                 <DataGridTemplateColumn Header="相關操作">
 5                     <DataGridTemplateColumn.CellTemplate>
 6                         <DataTemplate>
 7                             <Button Command={Binding Path=Edit}>編輯</Button>
 8                         </DataTemplate>
 9                     </DataGridTemplateColumn.CellTemplate>
10                 </DataGridTemplateColumn>
11             </DataGrid.Columns>
12         </DataGrid>

顯然這樣,Edit的Command是屬於AccountStore的,這樣位置就亂了。這里我們只需要設定它的RelativeSource就可以了。我們可以改成這樣

<UserControl x:Class="KnetSmartBox.ReportModule.Views.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <DataGrid ItemsSource="{Binding Path=AccountStore}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="賬戶名稱" Binding="{Binding Path=AccountName}"/>
                <DataGridTemplateColumn Header="相關操作">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                           <Button Command="{Binding Path=DataContext.Edit,RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">編輯</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</UserControl>

注意標黃的一段,自己理解一下。

這個屬性可以讓控件找尋DataContext,這里常用的有兩種方式,這里用的是AncestorType,也就是根據類型找,還可以根據級別找,就是AncestorLevel。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM