【问题标题】:WPF DataGrid Make Rows ReadOnly Based On PropertyWPF DataGrid 根据属性使行只读
【发布时间】:2020-05-21 09:27:12
【问题描述】:

我以编程方式将对象列表绑定到 DataGrid,如下所示:

gridAssetParameters.ItemsSource = asset.Parameters;

Parameters 是一个简单的类,具有三个属性:名称、值、描述和可编辑。将源设置为asset.Parameters时,这些列会自动生成,但是我面临的问题是我无法根据属性Editable将行设为只读。我正在考虑使用以下事件手动将行设为只读,但是无法循环生成的行或将行设置为只读。

private void GridAssetParameters_AutoGeneratedColumns(object sender, EventArgs e)
{
   //Somehow loop through rows and enable/disable based on logic
}

我知道 MVVM,但不确定在这种情况下如何使用它。任何建议将不胜感激!

更新

我的问题的答案在这里找到:

https://stackoverflow.com/a/17216605/1035217

【问题讨论】:

  • 除非你真的必须这样做,否则最好避免为数据网格自动生成列。或者直接在数据网格中编辑。我通常会做一个只读并在覆盖数据网格的面板中进行编辑。这样就可以在某个地方进行验证,并且很容易确保用户明确提交或放弃编辑。然后,当SelectedItem的IESEditia是假时,您可以禁用“编辑”按钮。 span>

标签: c# wpf


【解决方案1】:

如果你想在 XAML 中创建列

<DataGrid ItemsSource="{Binding Path=Parameters}" 
          AutoGenerateColumns="False" 
          IsReadOnly="True" 
          Name="ResultGrid"> 
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding Editable}"/>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns> 
        <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" Width="Auto"/> 
        <DataGridTextColumn Header="Value" Binding="{Binding Path=Value}" Width="*"/> 
        <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" Width="*"/> 
    </DataGrid.Columns> 
</DataGrid> 

如果你想自动生成列

<DataGrid ItemsSource="{Binding Path=Parameters}" 
          AutoGenerateColumns="True" 
          IsReadOnly="True" 
          Name="ResultGrid"> 
    <DataGrid.Resources>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding Editable}"/>
        </Style>
    </DataGrid.Resources>     
</DataGrid> 

【讨论】:

  • 使用这个我不能自动生成列?我仍在尝试了解数据模板和样式。很多人仍然停留在 WinForms 的思路中
  • @ceds:如果您愿意,可以查看更新后的答案。
  • Settings IsReadOnly = true 使所有行只读。将其设置为 false 不会给出所需的结果(所有行都是可编辑的)。这比我想象的要麻烦...
猜你喜欢
  • 2011-10-15
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 2023-03-19
  • 2011-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多