我正在尝试将数据更新同时用于XAML和XAML。即,当我在XAML TextBox中进行更改时,C#将接收新值,当我更改C#(通过单击按钮模拟)时,XAML TextBox都会更改。我有这个工作,但是如果我对XAML TextBox进行更改,它会更新XAML ItemsList。我有什么想法可以让它发挥作用吗?
... MainWindow.xaml
<Window x:Class="MySimpleProgram.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="725"
>
<StackPanel Name="StackPanel1" Orientation="Horizontal">
<TextBox Name="TextBox2" Text="{Binding Path=FirstName, Mode=TwoWay}" Height="23"/>
<Button Name="Button1" Content="Change C# obj people[0]" Width="175" Height="20" Click="Button1_Click" />
<ListBox Name="listPeople" DisplayMemberPath="FirstName"/>
</StackPanel>
</Window>
MainWindow.xaml.cs
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private String _FirstName;
public string FirstName
{
get { return _FirstName; }
set
{
_FirstName = value;
if (PropertyChanged != null)
PropertyChanged(
this, new PropertyChangedEventArgs("FirstName"));
}
}
public int Age { get; set; }
}
public partial class MainWindow : Window
{
public Person[] people;
public MainWindow()
{
InitializeComponent();
people = new Person[]{
new Person{ FirstName = "Shirley", Age = 22 },
new Person{ FirstName = "Roy", Age = 29 },
new Person{ FirstName = "Manuel", Age = 34 } };
StackPanel1.DataContext = people[0];
listPeople.ItemsSource = people;
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
people[0].FirstName += "y";
}
}
答案 0 :(得分:0)
在TextBox绑定上将 UpdateSourceTrigger
设置为 PropertyChanged
。
默认值为 LostFocus
,即丢失焦点的源更新,但如果您在键入时需要更新,请将其设置为PropertyChanged。,您将看到在ListBox中更新。
<TextBox Name="TextBox2"
Text="{Binding Path=FirstName, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"
Height="23"/>