C# wpfdatagrid到XML
我需要一个真正的帮助。我试图在wpf中编写一个用户可以编辑的datagrid。我已经完成了大部分工作,但我一直坚持将datagrid保存到xml并将其从xml加载到wtf 我将在我的代码上留下一些空白点,上面有“帮助注释”和一些关于我成功完成的操作的注释。考虑到我之前对c#和wpf一无所知,我对自己的成就感到非常自豪。遗憾的是,我也是xtml新手,对于我的具体问题没有好的教程材料 除“保存”和“加载”按钮外,所有按钮都可以工作 这是XAML文件C# wpfdatagrid到XML,c#,xml,wpf,datagrid,C#,Xml,Wpf,Datagrid,我需要一个真正的帮助。我试图在wpf中编写一个用户可以编辑的datagrid。我已经完成了大部分工作,但我一直坚持将datagrid保存到xml并将其从xml加载到wtf 我将在我的代码上留下一些空白点,上面有“帮助注释”和一些关于我成功完成的操作的注释。考虑到我之前对c#和wpf一无所知,我对自己的成就感到非常自豪。遗憾的是,我也是xtml新手,对于我的具体问题没有好的教程材料 除“保存”和“加载”按钮外,所有按钮都可以工作 这是XAML文件 <Window x:Class="
<Window x:Class="WpfAppLunes.MainWindow" <!-- This changes according to project name -->
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppLunes" <!-- This changes according to project name -->
mc:Ignorable="d" FontSize="18"
Title="WPF_Lunes" Height="500" Width="800">
<Border Padding="10">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Row 0 -->
<!-- Title of the Application -->
<TextBlock x:Name="BigHeader" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" TextWrapping="Wrap" Margin="1" FontSize="36" FontWeight="Bold" Text="Monthly Transactions" />
<DataGrid Grid.Row="1" AutoGenerateColumns="False" CanUserAddRows="False" x:Name="dgContent">
<DataGrid.Columns>
<DataGridTextColumn Header="Transaction Name" Binding="{Binding transactionName}"/>
<DataGridTextColumn Header="Amount '$'" Binding="{Binding Amount}"/>
</DataGrid.Columns>
</DataGrid>
<!--
<ListView Margin="10" Name="lvUsers" Grid.Row="1" Grid.ColumnSpan="2">
<ListView.View>
<GridView>
<GridViewColumn Header="Transaction Name" DisplayMemberBinding="{Binding transactionName}" />
<GridViewColumn Header="Amount '$'" DisplayMemberBinding="{Binding Amount}" />
</GridView>
</ListView.View>
</ListView>
-->
<TextBlock x:Name="TransactionHeader" Grid.Row="3" Grid.Column="0" TextWrapping="Wrap" Margin="1" Text="Transaction Name" />
<TextBlock x:Name="AmountHeader" Grid.Row="3" Grid.Column="1" TextWrapping="Wrap" Margin="1" Text="Amount" />
<!-- Row 3 -->
<!-- Text Boxes for the user to declare next item and its price -->
<TextBox x:Name="newTransaction" Grid.Row="4" Grid.Column="0" Padding="5" Margin="5"/>
<TextBox x:Name="newAmount" Grid.Row="4" Grid.Column="1" Padding="5" Margin="5" PreviewTextInput="newAmount_PreviewTextInput"/>
<ComboBox Grid.Row="4" Grid.Column="2" Name="Language" Width="170" Margin="1" VerticalContentAlignment="Center" VerticalAlignment="Top" MaxDropDownHeight="auto"></ComboBox>
<!-- <TextBox Text="{Binding Path=value, StringFormat={}{0:#.##}}" /> -->
<!-- Row 4 -->
<!-- Buttons to Add to the list or delete from the list -->
<Button x:Name="addButton" Click="addButton_Click" Grid.Row="5" Grid.Column="0" Margin="10" Content="Add" />
<Button x:Name="deleteButton" Click="deleteButton_Click" Grid.Row="5" Grid.Column="1" Margin="10" Content="Delete" />
<Button x:Name="changeButton" Content="Dil Değiştir" Margin="10" Grid.Column="3" Grid.Row="5" Click="changeButton_Click"/>
<!-- Row 5 -->
<!-- Save or Load the file -->
<Button x:Name="saveButton" Click="saveButton_Click" Grid.Row="6" Grid.Column="0" Margin="10" Content="Save" />
<Button x:Name="loadButton" Click="loadButton_Click" Grid.Row="6" Grid.Column="1" Margin="10" Content="Load" />
<!--Row 7 test for localization -->
</Grid>
</Border>
mc:Ignorable=“d”FontSize=“18”
Title=“WPF_Lunes”Height=“500”Width=“800”>
这是c#文件。
使用系统;
使用System.Collections.Generic;
使用System.Collections.ObjectModel;
使用系统组件模型;
使用系统数据;
使用System.Data.SqlClient;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Text.RegularExpressions;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
使用Finisar.SQLite;
使用System.Xml;
使用System.Xml.Linq;
使用System.IO;
//我试着用了很多东西,却懒得把它们拿走。如果您添加了其他内容,请发表评论
//请在它旁边。
名称空间WpfAppLunes
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
//我在这里初始化我的数据网格。
可观察到的采集对象;
公共主窗口()
{
初始化组件();
myObjects=新的可观察集合()
{
新交易(){transactionName=“Salary”,Amount=“$1670.00”},
新交易(){transactionName=“Car”,Amount=“-$60.00”},
新交易(){transactionName=“Clothing”,Amount=“-$320.00”},
新交易(){transactionName=“Food”,Amount=“-$85.00”},
新交易(){transactionName=“Leisure”,Amount=“-$35.00”},
新交易(){transactionName=“Living”,Amount=“-$560.00”}
};
this.dgContent.ItemsSource=myObject;
BindLanguage();
}
//这是我的组合框,用户可以从语言设置中进行选择
#区域绑定语言从和到组合框
私有语言()
{
DataTable dtCurrency=新DataTable();
//在DataTable中添加显示列
dtCurrency.Columns.Add(“文本”);
//在DataTable中添加值列
dtCurrency.Columns.Add(“值”);
dtCurrency.Rows.Add(“EN”,0);
dtCurrency.Rows.Add(“TR”,1);
Language.ItemsSource=dtCurrency.DefaultView;
Language.DisplayMemberPath=“Text”;
Language.SelectedValuePath=“Value”;
Language.SelectedIndex=0;
}
#端区
//它将事务名称和值添加到数据网格。它还格式化数据网格金额视图。
//添加按钮属性
私有void addButton_单击(对象发送方,路由目标)
{
双数量格式;
amountFormat=double.Parse(this.newAmount.Text);
如果(数量格式<0)
{
amountFormat*=-1;
transaction myObject=new transaction(){transactionName=this.newTransaction.Text,Amount=“-$”+amountFormat.ToString(“N2”)};
myObjects.Add(myObject);
}
其他的
{
事务myObject=new transaction(){transactionName=this.newTransaction.Text,Amount=“$”+amountFormat.ToString(“N2”)};
myObjects.Add(myObject);
}
}
//它将从数据网格中删除选定的值。
//删除按钮属性
私有void delete按钮\单击(对象发送方,路由目标)
{
如果(dgContent.SelectedIndex>=0)
{
//从集合源中删除selectedItem
所选事务=dgContent.SelectedItem作为事务;
myObjects.Remove(选定);
}
}
//保存按钮属性
私有无效保存按钮\u单击(对象发送方,路由目标)
{
/*帮助帮助帮助帮助*/
}
//加载按钮属性
//我认为在实际从xml加载文件之前清除datagrid是个好主意
//我认为创建一个新按钮来清除datagrid是个好主意。我稍后会添加它。
私有无效加载按钮\u单击(对象发送者,路由目标e)
{
/*帮助帮助帮助帮助帮助帮助帮助*/
myObjects.Clear();
}
//它获取文本框的值。
公共类事务
{
公共字符串transactionName{get;set;}
公共字符串金额{get;set;}
}
//确保用户只能输入+/-十进制值。
私人作废新金额
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Finisar.SQLite;
using System.Xml;
using System.Xml.Linq;
using System.IO;
//I tried to use a lot of stuffs and did not bother to remove them. If you add another, put a comment
//next to it please.
namespace WpfAppLunes
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//I initialize my datagrid here.
ObservableCollection<transaction> myObjects;
public MainWindow()
{
InitializeComponent();
myObjects = new ObservableCollection<transaction>()
{
new transaction(){transactionName = "Salary", Amount = "$1,670.00"},
new transaction(){transactionName = "Car", Amount = "-$60.00"},
new transaction(){transactionName = "Clothing", Amount = "-$320.00"},
new transaction(){transactionName = "Food", Amount = "-$85.00"},
new transaction(){transactionName = "Leisure", Amount = "-$35.00"},
new transaction(){transactionName = "Living", Amount = "-$560.00"}
};
this.dgContent.ItemsSource = myObjects;
BindLanguage();
}
//This is my combobox that lets the user choose from language settings
#region Bind Language From and To Combobox
private void BindLanguage()
{
DataTable dtCurrency = new DataTable();
//Add display column in DataTable
dtCurrency.Columns.Add("Text");
//Add value column in DataTable
dtCurrency.Columns.Add("Value");
dtCurrency.Rows.Add("EN", 0);
dtCurrency.Rows.Add("TR", 1);
Language.ItemsSource = dtCurrency.DefaultView;
Language.DisplayMemberPath = "Text";
Language.SelectedValuePath = "Value";
Language.SelectedIndex = 0;
}
#endregion
//It adds the transaction name and value to the data grid. It also formats the datagrid amount view.
//Add button properties
private void addButton_Click(object sender, RoutedEventArgs e)
{
double amountFormat;
amountFormat = double.Parse(this.newAmount.Text);
if (amountFormat < 0)
{
amountFormat *= -1;
transaction myObject = new transaction() { transactionName = this.newTransaction.Text, Amount = "-$" + amountFormat.ToString("N2") };
myObjects.Add(myObject);
}
else
{
transaction myObject = new transaction() { transactionName = this.newTransaction.Text, Amount = "$" + amountFormat.ToString("N2") };
myObjects.Add(myObject);
}
}
//It deletes the selected value from the data grid.
//Delete button properties
private void deleteButton_Click(object sender, RoutedEventArgs e)
{
if (dgContent.SelectedIndex >= 0)
{
//remove the selectedItem from the collection source
transaction selected = dgContent.SelectedItem as transaction;
myObjects.Remove(selected);
}
}
//Save button properties
private void saveButton_Click(object sender, RoutedEventArgs e)
{
/* HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP */
}
//Load button properties
//I thought it would be good idea to clear the datagrid before I actually load the file from xml
//I think it will be good idea to create a new button just to clear the datagrid. I will add it later.
private void loadButton_Click(object sender, RoutedEventArgs e)
{
/* HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP HELP */
myObjects.Clear();
}
//It gets the textbox values.
public class transaction
{
public string transactionName { get; set; }
public string Amount { get; set; }
}
//Makes sure that user can input only the +/- decimal values.
private void newAmount_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
//Because this line and next line comes before regex, they can be inputted.
//It will allow the user to add negative value
if (e.Text.Equals("-") && newAmount.Text.Length.Equals(0))
return;
//It will allow the user input 1 decimal point.
//User can input more than 2 numbers after the decimal point to my displeasure
//I did manage to get a workaround on this though. When the amount is added to the datagrid
//it will show in the way I want it to show.
if (e.Text.Equals(".") && !newAmount.Text.Contains("."))
return;
//This makes sure that user cannot enter anything other than number.
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
//It is my localization method.
//This is my version of localization. I could not get xaml change language because it would not recognize
//loc type variables for some reason. Maybe I missed some library. :D
//I would love it if someone told me the possible problem, but it is my last concern.
private void changeButton_Click(object sender, RoutedEventArgs e)
{
if (Language.Text == "EN" && changeButton.Content.ToString() == "Change Language")
{
changeButton.Content = "Dil Değiştir";
addButton.Content = "Add";
deleteButton.Content = "Delete";
saveButton.Content = "Save";
loadButton.Content = "Load";
TransactionHeader.Text = "Transaction Name";
AmountHeader.Text = "Amount";
dgContent.Columns[0].Header = "Transaction Name";
dgContent.Columns[1].Header = "Amount '$'";
BigHeader.Text = "Monthly Transactions";
}
if(Language.Text == "TR" && changeButton.Content.ToString() == "Dil Değiştir")
{
changeButton.Content = "Change Language";
addButton.Content = "Ekle";
deleteButton.Content = "Sil";
saveButton.Content = "Kaydet";
loadButton.Content = "Yükle";
TransactionHeader.Text = "İşlem";
AmountHeader.Text = "İşlem Miktarı";
dgContent.Columns[0].Header = "İşlem";
dgContent.Columns[1].Header = "İşlem Miktarı '$'";
BigHeader.Text = "Aylık Gelir/Giderler";
}
}
}
}
//Save button properties
private void saveButton_Click(object sender, RoutedEventArgs e)
{
var fileName = GetSaveFilePath();
var serializer = new XmlSerializer(typeof(List<transaction>));
using (TextWriter stream = new StreamWriter(fileName))
{
serializer.Serialize(stream, myObjects.ToList());
stream.Flush();
}
}
/// <summary>
/// Where you want to save data
/// </summary>
private string GetSaveFilePath()
{
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var fileName = System.IO.Path.Combine(desktop, "myData.xml");
return fileName;
}
//Load button properties
private void loadButton_Click(object sender, RoutedEventArgs e)
{
myObjects.Clear();
var fileName = GetSaveFilePath();
var serializer = new XmlSerializer(typeof(List<transaction>));
using (TextReader stream = new StreamReader(fileName))
{
var list = (List<transaction>)serializer.Deserialize(stream);
foreach (var item in list)
{
myObjects.Add(item);
}
}
}