Wpf Datagrid没有显示文本框数据?

时间:2014-04-29 09:47:26

标签: c# wpf xaml datagrid

嗨,我正在使用一个简单的wpf应用程序。我的问题是,我想在文本框中写一些东西,当我点击按钮时它会在datagrid中显示我。 我的代码是:

C#:

public partial class MainWindow : Window
    {
        public ObservableCollection<VLANS> vlan { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            vlan=new ObservableCollection<VLANS>();
            this.DataContext=this;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var item = new VLANS();
            item.vlanName = t1.Text;
            //dg.ItemsSource = vlanName;
            dg.ItemsSource = item.vlanName;
        }
    }

    public class VLANS
    {
        public string vlanName { get; set; }

    }
}

XAML:

<Window x:Class="TextboxToDatagridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"/>
            <RowDefinition Height="200"/>
        </Grid.RowDefinitions>
        <TextBox
            Name="t1"
            Grid.Row="0"
            Width="150"
            Height="50"
            Margin="200,0,0,0"
            />
        <Button
            Grid.Row="0"
            Width="150"
            Height="40"
            Content="Button" FontSize="25"
            HorizontalAlignment="Left"
            Margin="80,0,0,0" Click="Button_Click">
         </Button>
        <DataGrid
            Name="dg"
            Grid.Row="1">
            <DataGrid.Columns>
                <DataGridTextColumn
                Header="VLAN Name" Binding="{Binding Path=vlanName}"/>

            </DataGrid.Columns>
        </DataGrid>  

    </Grid>
</Window>

快照: enter image description here

问题出在哪里,如何将文本框数据传输到datagrid?任何帮助都会非常值得赞赏。

1 个答案:

答案 0 :(得分:1)

 private void Button_Click(object sender, RoutedEventArgs e)
 {
    var item = new VLANS();
    item.vlanName = t1.Text;

    vlan.Add(item);
 }

的Xaml:

<DataGrid ItemsSource="{Binding vlan}" AutoGenerateColumns="False" Grid.Row="1">
            <DataGrid.Columns>
                <DataGridTextColumn
                Header="VLAN Name" Binding="{Binding Path=vlanName}"/>

            </DataGrid.Columns>
</DataGrid>