[英]Default Value For WPF Datagrid Column
我的 WPF 應用程序中有一個 DataGrid。 我想知道是否有辦法顯示數據網格中列的默認值。 例如,我讓用戶能夠向 DataGrid 添加新行。 因此,在 DataGrid 的底部,總是有一個空白的空行供用戶添加數據。 我希望這一行中的列有一個默認值。 有什么辦法可以實現這個功能嗎? 謝謝!
假設您的DataGrid
的ItemsSource
是SomeClass
的集合,並且您在 DataGrid 列中顯示SomeClass
不同Properties
。 您可以做的是在默認SomeClass
構造函數中為Properties
分配一些默認值。 通過這種方式,您可以在 DataGrid 中擁有默認列值。
編輯
正如你所說,列的itemssource
是一個字符串,我能想到一種方法..
使它成為SomeClass
集合,它只有一個string
屬性。 在SomeClass
的默認構造函數中,為此字符串分配一個默認值。 該默認值將出現在您的數據網格列中
實際上,您可以在 ValueConverters 的幫助下做到這一點。 當 CanUserAddRows=True 時,行的 DataContext 綁定到 ItemsSource 的元素或綁定到空白行的 {DataGrid.NewItemPlaceholder}。
<DataGrid ItemsSource="{Binding Path=Collection}" CanUserAddRows=True >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource ShowSuitablePart}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
這是 ShowSuitablePart 轉換器的代碼。
public class ShowSuitablePart : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.ToString() == "{DataGrid.NewItemPlaceholder}")
return "This is blank row, just click me to create a new one";
else
((YourCollectionObject)value).SomeProperty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception();
}
}
如果需要雙向綁定,則必須在 DataTemplate 中使用 2 個元素。 一個用於空白行,第二個用於具有雙向綁定的常規行。 設置可見性綁定以隱藏常規行的第一個元素和空白行的第二個元素。
請記住,如果您確定集合對象的某些屬性的路徑,它不會在空行情況下引發 ValueConverter。
在 DataGrind 上創建一個 CheckBox 列並將其綁定到“myBoolColumn”
<DataGridCheckBoxColumn Header="Selected" Binding="{Binding myBoolColumn}" />
DataTable data = new DataTable();
data.Columns.Add("myBoolColumn", typeof(System.Boolean));
data.Columns["myBoolColumn"].DefaultValue = false;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.