Bind DataGrid TextBox Enable based on Checkbox property [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-13 04:31:32

问题


I have a DataGrid with a Checkbox & other Textbox.

   <DataGrid AutoGenerateColumns="False" Height="170" Name="dataGrid1" Width="527"  OpacityMask="#FF161A1A" BorderBrush="#FFB7B39D" Background="LightYellow" RowBackground="LightGray" AlternatingRowBackground="#FFFFFFF5" BorderThickness="10" CanUserResizeRows="False" CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserSortColumns="False" FontFamily="Segoe UI" FontSize="13" CanUserAddRows="False">

       <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="" Binding="{Binding BoolProperty, Mode=TwoWay}" />
            <DataGridTextColumn Header="" Binding="{Binding header}" MinWidth="108" IsReadOnly="True" />
            <DataGridTextColumn Header="Number of Cases" Binding="{Binding cases}" >
            <DataGridTextColumn.EditingElementStyle>
                  <Style TargetType="TextBox">
                        <Setter Property="IsEnabled" Value="{Binding Path=BoolProperty, Mode=TwoWay}" />
                 </Style>
           </DataGridTextColumn.EditingElementStyle>
          </DataGridTextColumn>

The checkboxcolumn is bind to a "BoolProperty". I want is Textbox "Number of Cases" to be disabled if the BoolProperty is false and enable if the BoolProperty is true. I tried adding the IsEnabled in TExtBox, but it doesn't work. Where am I going wrong ?


回答1:


For an XAML only approach, use a template column instead. IsReadOnly isn't bindable at the cell level. Since that link doesn't provide implementation, I will.

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=myProperty}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <TextBox IsEnabled="{Binding Path=myBool}" Text="{Binding Path=myProperty, Mode=TwoWay}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>



回答2:


I used the LoadingRow event of my DataGrid in one project to check specific status. Maybe something like this could help:

void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    checkRow(e.Row);
}

private void checkRow(DataGridRow dgRow)
{
    if (dgRow == null)
        return;

    var item = dgRow.Item as MyItemClass;
    if (item != null && item.BoolProperty)
    {
        ...
    }
    else
    {
        ...
    }
}

In your case you can enable/disable your cell in the if-else contruct.

Hope it helps.



来源:https://stackoverflow.com/questions/18443063/bind-datagrid-textbox-enable-based-on-checkbox-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!