1 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
“冒泡”是路由事件的概念。像 PropertyChanged 這樣的常規(guī)事件不會(huì)“冒泡”。
除了tnc = tnc;ViewModel 中的明顯錯(cuò)誤(應(yīng)該是this.tnc = tnc;)之外,這兩個(gè)類的 Test 屬性是不相關(guān)的。為了更新自己的 Test 屬性,ViewModel 必須在 處注冊(cè)一個(gè) PropertyChanged 事件處理程序tnc。并且它必須tnc在其自身的 Test 屬性更改時(shí)更新該屬性。
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestNotifyChanged tnc;
public ViewModel(TestNotifyChanged t)
{
tnc = t;
tnc.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Test) || string.IsNullOrEmpty(e.PropertyName))
{
Test = tnc.Test; // update ViewModel.Test from TestNotifyChanged.Test
}
};
}
private string test;
public string Test
{
get
{
return test; // always return own value
}
set
{
if (test != value)
{
test = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Test)));
tnc.Test = Test; // update TestNotifyChanged.Test from ViewModel.Test
}
}
}
}
或者,刪除 Test 屬性的支持字段并僅操作tnc.Test:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private TestNotifyChanged tnc;
public ViewModel(TestNotifyChanged t)
{
tnc = t;
tnc.PropertyChanged += (s, e) =>
{
if (e.PropertyName == nameof(Test) || string.IsNullOrEmpty(e.PropertyName))
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Test)));
}
};
}
public string Test
{
get { return tnc.Test; }
set { tnc.Test = Test; }
}
}
幸運(yùn)的是,這完全沒有必要。
相反,可能只是一個(gè)公共Tnc財(cái)產(chǎn),如
public class ViewModel
{
public TestNotifyChanged Tnc { get; }
public ViewModel(TestNotifyChanged tnc)
{
Tnc = tnc;
}
}
使用這樣的綁定:
<TextBlock Text="{Binding Tnc.Test}"/>
- 1 回答
- 0 關(guān)注
- 423 瀏覽
添加回答
舉報(bào)