[英]Show an empty row when itemssource is null in wpf datagrid
我正在使用mvvm在wpf中進行項目。 我只想在wpf數據網格上顯示一行以添加一個新項目,並且我有一個ItemsSource
但它為null
, canUserAddRows
設置為true。
提前致謝。
您需要某種not null
的ItemsSource
。 只需初始化您的ObservableCollection<yourType>
。
最簡單的方法是通過ViewModel的構造函數來實現:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
_yourCollection = new ObservableCollection<yourType>();
//Now Items can be added, via code behind, or UI !
}
}
想一想 :您不能在null
對象上調用.Add()
(將拋出NullReferenceException
)。 因此,控件本身應如何通過UI允許它-沒有值可存儲在!
例:
視圖模型:
public class ViewModel
{
public ObservableCollection<Model> Collection { get; set;}
public ViewModel()
{
Collection = new ObservableCollection<Model>();
//Now Items can be added, via code behind, or UI !
}
}
模型:
public class Model
{
public string Text { get; set; }
}
XAML:
<DataGrid CanUserAddRows="True"
AutoGenerateColumns="False"
IsReadOnly="False"
ItemsSource="{Binding Collection}">
<DataGrid.Columns>
<DataGridTextColumn Width="*"
Header="Value"
Binding="{Binding Text}"/>
</DataGrid.Columns>
</DataGrid>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.