【发布时间】:2013-06-15 16:27:45
【问题描述】:
我的项目是这样的,http://s23.postimg.org/mrhuocn4b/asd.png
我已经可以使用以下代码将文本框保存到 xml 文件:
private void SaveFile(object sender, RoutedEventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "xml";
saveFileDialog.Filter = "XML Files (*.xml)|*.xml|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == true)
{
using (Stream stream = saveFileDialog.OpenFile())
{
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.UTF8);
sw.Write(GetGeneratedXML().ToString());
sw.Close();
stream.Close();
}
}
}
private XElement GetGeneratedXML()
{
XElement userInformation = new XElement("names");
userInformation.Add(new XElement("first", box1.Text));
// userInformation.Add(new XElement("last", lastNameText.Text));
return userInformation;
}
但这是来自已在 XAML 中创建的文本框(我仅用于测试),我想要保存通过单击按钮创建的所有文本框的文本。
这就是我创建文本框的方式:
XAML:
<TextBox Text="{Binding Header,UpdateSourceTrigger=PropertyChanged}"
BorderBrush="Black" BorderThickness="1" />
<TextBox Text="{Binding Text,UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
AcceptsReturn="True"
BorderBrush="Black" BorderThickness="1" Grid.Row="1" />
C#:
private void b_ClickEntidade(object sender, RoutedEventArgs e)
{
MyBox c = new MyBox();
c.Header = "Entidade";
c.Text = "Atributos";
c.Margin = new Thickness(10);
c.BorderThickness = new Thickness(1);
LayoutRoot.Children.Add(c);
c.MouseLeftButtonDown += Handle_MouseDownEntidade;
c.MouseMove += Handle_MouseMoveEntidade;
c.MouseLeftButtonUp += Handle_MouseUpEntidade;
Canvas.SetLeft(c, 250);
Canvas.SetTop(c, 40);
}
编辑-----------
这是 MyBox.cs
public partial class MyBox : UserControl
{
public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(MyBox),null);
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Content", typeof(string), typeof(MyBox), null);
public string Header
{
get { return GetValue(HeaderProperty) as string; }
set { SetValue(HeaderProperty, value); }
}
public string Text
{
get { return GetValue(TextProperty) as string; }
set { SetValue(TextProperty, value); }
}
public MyBox()
{
InitializeComponent();
this.DataContext = this;
}
}
}
【问题讨论】:
-
有一个错字(我的错误):应该是“... TextProperty = DependencyProperty.Register("Text",..." 不应该解决您的问题,而是朝着正确方向迈出的一步. :)
-
在调试时检查是否有一些绑定错误出现在输出中。并尝试中断任何方法,例如事件处理程序并选中复选框,它们没有理由不更新。
-
我发现了错误,-> TextBox Text="{Binding Header,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}",缺少 mode=twoway.. 再次感谢您的帮助 :)
-
顺便说一句,你知道连接盒子的更好方法吗?现在我正在按照你在图片中看到的方式连接它们,但是当我移动盒子时,我需要分别移动连接..这个问题就在这里 -> stackoverflow.com/questions/17047624/…
-
至于绑定,这是因为在 Silverlight 中绑定默认为 OneWay,而在 WPF 中,某些绑定默认为 TwoWay,如 TextBox.Text,因为这是 99% 的时间您想要的。我在 WPF 中进行测试,因为 ... 一段时间没有使用 SL :)
标签: xml silverlight save export