Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
Mình có một vấn đề về binding như sau: Mình có class A và tạo biến class A với tên a trong MainWindow. Trong class A có biến String str = "ND", khi str thay đổi giá trị thì Textbox tb cũng thay đổi theo. Nhưng khi mình tạo thêm class B có chứa biến String str = "ND" và biến B b được tạo trong Class A, giờ mình binding đến a.b.str thì Textbox tb chỉ cập nhật lần đầu chạy, nhưng lần thay đổi giá trị tiếp theo nó không cập nhật nữa mặc dù khi thay đổi giá trị trong tb thì str vẫn thay đổi theo.
Mọi người xem giúp với!
public class B : INotifyPropertyChanged
{
string str;
public string Str
{
set
{
this.value = str;
OnPropertyChanged("Str");
}
get
{
return this.value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
}
public class A : INotifyPropertyChanged
{
B b1;
public B b
{
set
{
this.b1= value;
OnPropertyChanged("b");
}
get
{
return this.b1;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
}
public partial class MainWindow
{
A a= new A(1);
public MainWindow()
{
InitializeComponent();
Binding myBinding = new Binding();
myBinding.Path = new PropertyPath("Str");
myBinding.Source = a.b;
myBinding.Mode = BindingMode.TwoWay;
BindingOperations.SetBinding(tb, TextBox.TextProperty, myBinding);
BindingOperations.SetBinding(Up, Button.ContentProperty, myBinding);
}
private void Up_Click(object sender, RoutedEventArgs e)
{
a.b.Str += 1;
}
}
Đã hiểu nguyên nhân do biến mình cần binding trong project mình làm có kiểu dữ liệu là double :)).
Nhưng giờ có một vấn đề phát sinh là làm sao để binding đến một phần tử trong mảng động.
myBinding.Source = a.B chứ bạn nhỉ