WPF DataGrid问题:为什么数据输出两次?

时间:2013-08-14 16:30:37

标签: wpf mvvm binding datagrid

我是WPF编程的新手。我写了一个关于WPF DataGrid控件的简单示例并使用MVVM模式。我想要做的是在DataGrid控件中显示数据。但是,数据总是在数据网格中重复。输出如下图所示: enter image description here

代码段:

// Model: 
Public class Machine
{
    Private string _uuid;
    public string UUID {get{ return _uuid; } set{ _uuid = value; }}
    public Targets(string uuid)
    {
         UUID = uuid;
    }
 }


// ViewModel:
public class MainWindowViewModel
{
    private readonly ObservableCollection<Machine> _machine = new ObservableCollection<Machine>();
    public MainWindowViewModel()
    {
        _machine.Add(new Machine("1234"));
    }
    public ObservableCollection< Machine > Machines
    {
        get { return _machine; }
    }
}

// XAML:
<DataGrid Name="datagGrid1" Margin="2,2,2,2" ItemsSource="{Binding Machines}" IsReadOnly="True">
     <DataGrid.Columns>
           <DataGridTextColumn Width="120"
                           Binding="{Binding UUID}"
                       Header="UUID-S" />
     </DataGrid.Columns>
 </DataGrid>

1 个答案:

答案 0 :(得分:3)

您需要在XAML中设置AutoGenerateColumns="False"

<DataGrid AutoGenerateColumns="False" Name="datagGrid1" Margin="2,2,2,2" ItemsSource="{Binding Machines}" IsReadOnly="True">
    <DataGrid.Columns>
        <!-- ...