在我的程序中,我有一个包含 DataGrid
的 UserControl有它的ItemsSource
绑定(bind)到 ObservableCollection
.为此DataGrid
我需要能够禁用和灰显特定的单元格。我想最好在 C++ 中执行此操作,因为我可能需要更改在运行时发生的单元格。我知道如何使用IsReadOnly
,但似乎我只能为整个列切换它。这成为一个问题,因为我的列绑定(bind)到数据,这使我更难定位特定的网格单元。
话虽如此,
XAML:
<DataGrid ItemsSource="{Binding Model.Collection}" ... >
<DataGrid.Columns>
<!-- Row Number -->
<DataGridTextColumn Width="SizeToCells" IsReadOnly="True" Binding="{Binding rowNum}" />
<!-- Inputs -->
<DataGridTextColumn Width="SizeToCells" IsReadOnly="False" Header="Inputs" Binding="{Binding input}" />
<!-- Outputs -->
<DataGridTextColumn Width="SizeToCells" IsReadOnly="False" Header="Outputs" Binding="{Binding output}" />
</DataGrid.Columns>
</DataGrid>
数据模型:
namespace Program.Data_Models
{
public class CartIO_Model : PropertyChangedBase
{
private string test1 = "One";
private string test2 = "Two";
private string test3 = "Three";
private string DISABLEDtest4 = "Four";
private string DISABLEDtest5 = "Five";
private ObservableCollection<collectionData> _collection;
public CartIO_Model()
{
Collection = new ObservableCollection<collectionData>();
Collection.Add(new collectionData() { rowNum = 0, input = test1, output = ""});
Collection.Add(new collectionData() { rowNum = 1, input = test2, output = ""});
Collection.Add(new collectionData() { rowNum = 2, input = "", output = test3 });
Collection.Add(new collectionData() { rowNum = 3, input = "", output = DISABLEDtest4 });
Collection.Add(new collectionData() { rowNum = 4, input = DISABLEDtest5, output = ""});
}
public ObservableCollection<collectionData> Collection
{...}
}
public class collectionData
{
public int rowNum { set; get; }
public string input { set; get; }
public string output { set; get; }
}
}
我将在哪里以及如何控制启用/禁用哪些单元格?这让我很困惑,因为
IsEnabled
是 View 控件的特征,而不是 ObservableCollection
的特征。 .
最佳答案
您可以定义CellStyle
为您的列并根据模型或 View 模型中的任何数据启用/禁用单元格。在这里,我禁用了 Inputs 列中输入值为 Test4 的所有单元格
<DataGrid ItemsSource="{Binding Model.Collection}" >
<DataGrid.Columns>
<!-- Row Number -->
<DataGridTextColumn Width="SizeToCells" Binding="{Binding rowNum}">
</DataGridTextColumn>
<!-- Inputs -->
<DataGridTextColumn Width="SizeToCells" Header="Inputs" Binding="{Binding input}" >
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding input}" Value="Four">
<Setter Property="IsEnabled" Value="false"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<!-- Outputs -->
<DataGridTextColumn Width="SizeToCells" IsReadOnly="False" Header="Outputs" Binding="{Binding output}" />
</DataGrid.Columns>
</DataGrid>
关于c# - 如何在绑定(bind)到 ObservableCollection 时禁用 DataGrid 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19572984/