简体   繁体   English

WPF DataGrid 根据属性使行只读

[英]WPF DataGrid Make Rows ReadOnly Based On Property

I'm binding a list of objects to a DataGrid programatically as follows:我正在以编程方式将对象列表绑定到 DataGrid,如下所示:

gridAssetParameters.ItemsSource = asset.Parameters;

Parameters is a simple class with three properties: Name, Value, Description and Editable.参数是一个简单的类,具有三个属性:名称、值、描述和可编辑。 The columns generate automatically when setting the source to asset.Parameters, however the problem that I'm facing is I cannot make a row readonly based on the property Editable.将源设置为 asset.Parameters 时,这些列会自动生成,但是我面临的问题是我无法根据属性 Editable 将行设为只读。 I was thinking of using the below event to manually make the rows readonly, however there is no way of looping through the generated rows or settings rows as readonly.我正在考虑使用以下事件手动将行设置为只读,但是无法将生成的行或设置行循环为只读。

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

I am aware of MVVM however am unsure of how to use it in this case.我知道 MVVM 但不确定如何在这种情况下使用它。 Any advice will be appreciated!任何建议将被认真考虑!

UPDATE更新

Answer to my question was found here:我的问题的答案在这里找到:

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

If you want to create columns in XAML如果要在 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> 

If you want to auto generate columns如果要自动生成列

<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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM