簡體   English   中英

WPF Datagrid自動增量列生成錯誤的值?

[英]Wpf datagrid auto-increment column generating wrong values?

嗨,我正在一個簡單的WPF應用程序上工作。我的問題是我想包括序列號(S_No)列,該列應自動遞增,但顯示異常值。 我想要適當的串行列作為我的第一列。 我的代碼是:

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



            dg.ItemsSource =vlan;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var serial = new VLANS();
            serial.S_No = vlan.Count;
            vlan.Add(serial);

            var vname = new VLANS();
            vname.VlanName = t1.Text;
            vlan.Add(vname);



        }
    }

    public class VLANS
    {
        public string VlanName { get; set; }
        public int S_No { 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
            AutoGenerateColumns="False"
            Name="dg"
            Grid.Row="1">
            <DataGrid.Columns >
                <DataGridTextColumn Header="S.No" Binding="{Binding Path=S_No}" />
                <DataGridTextColumn Header="Vlan Name" Binding="{Binding Path=VlanName}"/>

            </DataGrid.Columns>

        </DataGrid>  

    </Grid>
</Window>

捕捉是: 在此處輸入圖片說明

誰能告訴我我在哪里。 任何幫助將受到高度贊揚。

問題出在您的事件處理程序上,而不是您嘗試的操作上

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var serial = new VLANS();
        vlan.Add(serial)
        serial.S_No = vlan.Count;
        serial.VlanName = t1.Text;
        vlan.Add(serial);

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM