我是MVVM的新手。我在我的项目中使用wpf和MVVM。所以我现在正在测试一些东西,然后再深入了解我需要编写的应用程序。
我的页面(EmpDetailsWindow.xaml)就像这样
<Grid>
<DataGrid Name="dgEmployee" Grid.Row="0" AutoGenerateColumns="True" ItemsSource="{Binding EmployeeDataTable}" CanUserAddRows="True" CanUserDeleteRows="True" IsReadOnly="False" />
<Button x:Name="btnSubmit" Content="Submit" Command="{Binding SubmitCommand}" CommandParameter="sample param" HorizontalAlignment="Left" Margin="212,215,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
和我的模型(EmpDetailsWindowViewModel)如下
public class EmpDetailsWindowViewModel : INotifyPropertyChanged
{
public ICommand SubmitCommand { get; set; }
public EmpDetailsWindowViewModel()
{
EmployeeDataTable = DataTableCreator.EmployeeDataTable();
GenderDataTable = DataTableCreator.GenderDataTable();
SubmitCommand = new SubmitCommand();
}
DataTable _employeeDataTable;
public DataTable EmployeeDataTable
{
get { return _employeeDataTable;}
set
{
_employeeDataTable = value;
RaisePropertyChanged("EmployeeDataTable");
}
}
DataTable _genderDataTable;
public DataTable GenderDataTable
{
get { return _genderDataTable; }
set
{
_genderDataTable = value;
RaisePropertyChanged("GenderDataTable");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
datagrid已成功绑定到数据表。现在我在datagrid中有一个“Gender”列。这应该是一个组合框,cobobox的项目源来自视图模型的GenderDataTable。我怎样才能做到这一点?
答案 0 :(得分:5)
你可以这样做
<DataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "Gender")
{
var cb = new DataGridComboBoxColumn();
cb.ItemsSource = (DataContext as MyVM).GenderDataTable;
cb.SelectedValueBinding = new Binding("Gender");
e.Column = cb;
}
}
答案 1 :(得分:0)
在Infragistics xamDataGrid中,您可以通过在FieldLayoutInitialized事件中编写适当的逻辑来以编程方式设置它。
请参阅此链接以获取更多信息:
答案 2 :(得分:0)
这里似乎还没有一个完整的答案,因此我将发布从这个问题和实验中发现的内容。我敢肯定,这违反了许多规则,但它很简单而且可以正常工作
public partial class MainWindow : Window
{
// define a dictionary (key vaue pair). This is your drop down code/value
public static Dictionary<string, string>
dCopyType = new Dictionary<string, string>() {
{ "I", "Incr." },
{ "F", "Full" }
};
// If you autogenerate columns, you can use this event
// To selectively override each column
// You need to define this event on the grid in the event tab in order for it to be called
private void Entity_AutoGeneratingColumn(object sender,
DataGridAutoGeneratingColumnEventArgs e)
{
// The name of the database column
if (e.PropertyName == "CopyType")
{
// heavily based on code above
var cb = new DataGridComboBoxColumn();
cb.ItemsSource = dCopyType; // The dictionary defined above
cb.SelectedValuePath = "Key";
cb.DisplayMemberPath = "Value";
cb.Header = "Copy Type";
cb.SelectedValueBinding = new Binding("CopyType");
e.Column = cb;
}
}
} // end public partial class MainWindow