我試圖讓數據綁定在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