【问题标题】:DataBinding in to object in List数据绑定到列表中的对象
【发布时间】:2013-11-22 19:43:48
【问题描述】:

我遇到了一个问题,我有一个对象列表,比如说 Person:

class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _name;
    private string _surname;
    public string name
    {
        get { return _name; }
        set { SetField(ref _name, value, "name"); }

    }
    public string surname
    {
        get { return _surname; }
        set { SetField(ref _surname, value, "surname"); }

    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));

        }
    }
    protected bool SetField<T>(ref T field, T value, string propertyName)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }
}

还有 XAML:

<TextBlock HorizontalAlignment="Left" Margin="310,167,0,0" TextWrapping="Wrap" Text="{Binding Path=name}" VerticalAlignment="Top" FontSize="36"/>
    <TextBlock HorizontalAlignment="Left" Margin="585,167,0,0" TextWrapping="Wrap" Text="{Binding Path=surname}" VerticalAlignment="Top" FontSize="36"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="721,355,0,0" VerticalAlignment="Top" Click="Button_Click"/>

在页面初始化我这样做:

List<Person> Persons = new List<Person>();
    public MainPage()
    {
        this.InitializeComponent();

        Person a = new Person();
        a.name = "First";
        a.surname = "FirstSurname";
        Persons.Add(a);
        Person b = new Person();
        b.name = "Second";
        b.surname = "SecondSurname";
        Persons.Add(b);
        this.DataContext = Persons[0];
    }

我不想改变属性,而是改变整个对象:

private void Button_Click(object sender, RoutedEventArgs e)
    {

        Person a = new Person();
        a.name = "Test";
        a.surname = "Test";
        Persons[0] = a;
    }

如何让我的 TextBlocks 自动重新获取数据?不这样做。DataContext = Persons[0];再次

【问题讨论】:

  • 当您只想绑定到第一个元素时,为什么会有List&lt;Person&gt;?为什么在MainPage 中没有CurrentPerson 属性(带有更改通知)?

标签: c# xaml data-binding datasource


【解决方案1】:

TextBlockText 属性中,尝试将 UpdateSourceTrigger 设置为 PropertyChanged

Text="{Binding Path=name, UpdateSourceTrigger=PropertyChanged}"

【讨论】:

  • 错误 1 ​​元素“绑定”上的未知成员“UpdateSourceTrigger”c:\users\afomenko\documents\visual studio 2012\Projects\App5\App5\MainPage.xaml 12 88 App5
  • 但无论如何也无济于事,因为我不是在更改属性,而是在更改整个对象
  • 您是否将两个 TextBlocks 和 Button 包裹在 DataTemplate 或其他东西上?我假设您列表中Persons 的数量会动态变化。如果您有一个带有 TextBlocks 和 Button 的 DataTemplate,您可以将其 ItemsSource 设置为列表并将其 UpdateSourceTrigger 设置为 PropertyChanged
猜你喜欢
  • 2010-10-10
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
相关资源
最近更新 更多