我想批量更新Person数据。
public class Person
{
public long personID { get; set; }
public long FirstName { get; set; }
public long LastName { get; set; }
public long Department { get; set; }
}
列出m_list = new List();
我有一个TextBox“TextBox1”控件,我想绑定到m_list的每个Person的“Department”属性。
foreach(Person current in m_list)
{
//string bindingPath = "Department";
//Binding binding = new Binding(bindingPath);
//binding.Mode = BindingMode.TwoWay;
//binding.Source = current;
//TextBox1.SetBinding(TextBox1.Text, binding);
}
答案 0 :(得分:0)
在你的视图模型中很容易做到这样的事情:
public class MainViewModel
{
private readonly Lazy<ObservableCollection<Person>> _people = new Lazy<ObservableCollection<Person>>(
() =>
{
return new ObservableCollection<Person>
{
new Person {Department = "Dept1", FirstName = "Person", LastName = "1"},
new Person {Department = "Dept2", FirstName = "Person", LastName = "2"},
};
});
public ObservableCollection<Person> People { get { return _people.Value; } }
public string Department
{
set
{
foreach (var p in People)
p.Department = value;
}
}
}
示例XAML:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Text="{Binding Department, UpdateSourceTrigger=PropertyChanged}" />
<ListView ItemsSource="{Binding People}" Grid.Column="1">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical" Margin="0,0,0,15">
<TextBlock Text="{Binding Department}"/>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
答案 1 :(得分:0)
我认为你可能会误解DataContext
WPF应用程序包含两个层:UI层和数据层。 DataContext
是数据层,而您的控件(例如TextBox
)是UI图层。
如果要批量更新数据,只需在数据层中执行更新即可。您根本不需要涉及UI层(除非您从中获取值)。
例如,如果您只有一个TextBox
,并且想要将Department
中每个Person
的{{1}}属性设置为List<Person>
,那么只需遍历您的TextBox.Text
列表,并将每个Person
属性设置为Department
TextBox1.Text