DatagridTemplateColumn复选框绑定在viewmodel上搜索属性

时间:2017-02-03 16:32:36

标签: wpf

在下面的代码片段中,我有一个在viewmodel上搜索“Checked”的绑定。但它不在我的ViewModel中,而是在我的DataGrid ItemsSource中的项目上。

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Center">
                <CheckBox IsChecked="{Binding Checked, UpdateSourceTrigger=PropertyChanged}" />
            </ContentControl>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

如何使绑定使用ItemsSource中的项目? 我搜索了高低,但找不到问题......

编辑:DataGrid绑定:

<DataGrid MaxHeight="250" VerticalScrollBarVisibility="Auto" ItemsSource="{Binding Questions}" CanUserAddRows="False" AutoGenerateColumns="False" Width="Auto">
    <DataGrid.Columns>
        <DataGridTemplateColumn ..... etc.. above snippet here
        ...
        </DataGridTemplateColumn.....
    </DataGrid.Columns>
</DataGrid>

视图模型:

public class Question
{
    public bool Checked { get; set; }
    public string Text { get; set; }

    /// <summary>
    /// Answers to show if the Question is checked
    /// </summary>
    public List<Answer> Answers { get; set; }
}

public class MyViewModel : ViewModelBase
{
    private readonly IEnumerable<Question> _Questions;
    /// <summary>
    /// Questions for Definition of Done
    /// </summary>
    public IEnumerable<Question> Questions
    {
        get
        {
            return _Questions;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果Checked属性实际上属于您已设置或绑定DataGrid的ItemsSource属性的T的类型IEnumerable<T>,则绑定应该有效。确保源属性的名称为“已检查”,并且它具有公共getter和setter。

如果Checked属性属于视图模型,您可以使用RelativeSource绑定它:

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <ContentControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Center">
                <CheckBox IsChecked="{Binding DataContext.Checked, RelativeSource={RelativeSource AncestorType=DataGrid}, UpdateSourceTrigger=PropertyChanged}" />
            </ContentControl>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>