0

我想批量更新人员数据。

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);
}
4

2 回答 2

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>
于 2012-07-18T18:41:16.800 回答
0

我想你可能误解了DataContext

WPF 应用程序包含两层:UI 层和数据层。是数据层,而DataContext您的控件(例如 a TextBox)是 UI 层。

如果要批量更新数据,只需在数据层中执行更新即可。您根本不需要涉及 UI 层(除非您从中获得价值)。

例如,如果您有一个单曲TextBox,并且您想在 to 中设置 every 的属性DepartmentPerson那么只需循环遍历您的列表,并将每个属性设置为List<Person>TextBox.TextPersonDepartmentTextBox1.Text

foreach(Person current in m_list)
{
    current.Department = TextBox1.Text;
}
于 2012-07-18T18:45:31.210 回答