如何使用mvvm在wpf中的datagrid中更改isReadOnly单元格

时间:2014-10-14 06:53:26

标签: c# wpf xaml mvvm datagrid

我的网格如下。

我想要的是当点击数据网格中的复选框时,如果选中了True Holoday Name应该启用,否则它应该是可编辑的。



<DataGrid CanUserDeleteRows="False" CanUserAddRows="False" Name="dgwCalenderDetails" SelectionMode="Single" ItemsSource="{Binding CalenderDetails, Mode=TwoWay}" IsReadOnly="False" AutoGenerateColumns="False" Width="770">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Day Id" Binding="{Binding DayId}" Visibility="Hidden" IsReadOnly="False" />
        <DataGridTextColumn Header="Day" Binding="{Binding DayName}" Width="100" IsReadOnly="False"/>
        <DataGridTextColumn Header="Date" Binding="{Binding DisplayDate, StringFormat={}{0:dd/MM/yyyy}}" Width="75" IsReadOnly="False"/>
        <DataGridTextColumn Header="Start Time" Binding="{Binding StartTime, StringFormat=N2}" Width="100" IsReadOnly="False"/>
        <DataGridTextColumn Header="Working Hours" Binding="{Binding NoOfWorkingHrs, StringFormat=N2}" Width="100" IsReadOnly="False"/>
        <DataGridCheckBoxColumn  Header="Holiday Status" Binding="{Binding IsHolidayYN}" Width="100" CanUserReorder="False"/>
        <DataGridTextColumn Header="Holoday Name" Binding="{Binding HolidayName}" Width="*" IsReadOnly="False" />
    </DataGrid.Columns>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Background" Value="White"/>
            <Setter Property="IsEnabled" Value="True"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsHolidayYN}" Value="true">
                    <Setter Property="Background" Value="Gray"/>
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
</DataGrid>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

<DataGridTextColumn Binding="{Binding HolidayName}" >
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="IsEnabled" Value="{Binding IsHolidayYN}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

答案 1 :(得分:0)

将属性绑定到列的IsReadOnly属性。处理复选框选中的事件并更新绑定到事件

中的列的属性

答案 2 :(得分:0)

在viewModel中生成cellEditEnding事件并在里面检查checkboxColumn的状态。如果选中,则查找列并设置为true;类似的东西:

public void CellEditEndingEvent(object Sender, DataGridCellEditEndingEventArgs e)
{  
    if(String.Equals(e.Column.Header.ToString(), "YourCheckBoxFieldName")
    {
        var x = e.Row.Item as YourType;
        if(null != x)
        {
            e.EditingElement.IsEnabled = x.IsHolidayYN;
        }
    }            
}

要在viewModel中获取此方法,请使用交互性和交互库。而且我没有测试代码。