我试图让数据绑定在WPF成立。我已经得到了类人,这是通过所述一个文本框更新(旧校园-等),以及其他文本框被认为反映通过数据绑定的改变的人对象(它使用的是一个型=双向但投掷一个xamlparseexception)。它不能这样工作,并点击显示person.name的按钮,它显示正确的名称,但文本框不会通过数据绑定更新。这是尝试理解数据绑定的不好方法吗?如果你有一个更好的方法来测试它,我完全可以放弃这个代码,然后去做。WPF中的DataBinding?
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:PeoplePleaser x:Key="PeoplePleaser" />
</Window.Resources>
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<TextBox Height="125" HorizontalAlignment="Left" Margin="81,122,0,0" Name="textBox1" VerticalAlignment="Top" Width="388" FontSize="36" Text="{Binding Converter={StaticResource PeoplePleaser}, Mode=OneWay}" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="209,39,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" TextChanged="textBox2_TextChanged" />
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public static Person myPerson = new Person();
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show(myPerson.name);
}
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
myPerson = new Person(textBox2.Text);
}
}
public class Person
{
public String name;
public Person()
{
new Person("Blarg");
}
public Person(String args)
{
if (!args.Equals(null))
{
this.name = args;
}
else new Person();
}
public Person(String args, Person argTwo)
{
argTwo = new Person(args);
}
}
public class PeoplePleaser : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
return MainWindow.myPerson.name;
}
catch (Exception e)
{
return "meh";
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!value.Equals(null))
{
return new Person(value.ToString(), MainWindow.myPerson);
}
else
{
return(new Person("", MainWindow.myPerson));
}
}
}
如果有许多错误链接到[相关概述(http://msdn.microsoft.com/en-us/library/ms752347.aspx)从来都不是一个错误,我认为。 –
感谢你们两位! – humanstory