如果ItemsSource已经在DataGrid上绑定,如何将数据绑定到DataGridTemplateColumn?

时间:2015-07-01 14:05:11

标签: c# wpf mvvm datagrid

我有一个DataGrid,它绑定到一个列表如下。

观点:

<DataGrid Name="m_dgWorkItems" ItemsSource="{Binding WorkItems}" AutoGenerateColumns="False" CanUserAddRows="False" Margin="12,70,12,12">
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Header="Selected" Binding="{Binding Selected}" />
        <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True" />
        <DataGridTextColumn Header="Summary" Binding="{Binding Summary}" IsReadOnly="True" />
        <DataGridTextColumn Header="State" Binding="{Binding State}" IsReadOnly="True" />
        <DataGridTextColumn Header="Owner" Binding="{Binding Owner}" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

ViewModel:

public List<WorkItem> WorkItems
{
    get { return m_workItems; }
    private set { m_workItems = value; RaisePropertyChanged("WorkItems"); }
}

public class WorkItem
{
    public bool Selected { get; set; }

    public string Id { get; set; }
    public string Summary { get; set; }
    public string State { get; set; }
    public string Owner { get; set; }
    public string Description { get; set; }
}

我想在标题中添加一个(Un)SelectAll选项,并将其绑定到DataContext的方法。

因此,我更改了视图:

<DataGrid Name="m_dgWorkItems" ItemsSource="{Binding WorkItems}" AutoGenerateColumns="False" CanUserAddRows="False" Margin="12,70,12,12">
    <DataGrid.Columns>
        <!--<DataGridCheckBoxColumn Header="Selected" Binding="{Binding Selected}" />-->
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.Header >
                <CheckBox Content="Selected" IsChecked="{Binding IsAllChecked, Mode=TwoWay}"></CheckBox>
            </DataGridTemplateColumn.Header>
            <DataGridTemplateColumn.CellTemplate >
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Selected}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Id" Binding="{Binding Id}" IsReadOnly="True" />
        <DataGridTextColumn Header="Summary" Binding="{Binding Summary}" IsReadOnly="True" />
        <DataGridTextColumn Header="State" Binding="{Binding State}" IsReadOnly="True" />
        <DataGridTextColumn Header="Owner" Binding="{Binding Owner}" IsReadOnly="True" />
    </DataGrid.Columns>
</DataGrid>

我将此功能添加到ViewModel:

public bool IsAllChecked
{
    get { return m_bIsAllChecked; }
    set
    {
        m_bIsAllChecked = value;
        foreach (WorkItem workItem in m_workItems)
            workItem.Selected = value;
        RaisePropertyChanged("IsAllChecked");
    }
}

但是,程序永远不会进入该功能。我认为这是由于 WorkItem 属性不包含 IsAllChecked 属性。 我不知道如何指定绑定应该应用于 DataContext 而不是当前 ItemsSource =&#34; {Binding WorkItems}&#34;

0 个答案:

没有答案